//
//  HeaRateViewCtrl.m
//  AccuroFit
//
//  Created by Yongfeng Li on 8/11/15.
//  Copyright (c) 2015 Nci Technology Inc. All rights reserved.
//

#import <AudioToolbox/AudioServices.h>
#import "AppDelegate.h"
#import "HeaRateViewCtrl.h"
#import "UIView+ALQuickFrame.h"

#import "H_Rate.h"
#import "H_RateRng.h"
#import "H_RateItem.h"

#import "ViewController.h"
#import "UIView+Extension.h"
#import "O-Hrate.h"
#import "O-HrateItem.h"

#define kBatteryFillWidth 36.0
#define kiPadBatteryFillWidth 55.0
#define kOnePercent kBatteryFillWidth / 100
#define kiPadOnePercent kiPadBatteryFillWidth / 100
#define __nSyncPackCount 8

#define _BarHgtUpLimit 40
#define DefaultColor  [UIColor colorWithRed:0.44 green:0.18 blue:0.53 alpha:1.00];
static NSString* _sCurrUuId = @"";
static NSString* _sCurBleConn = @"";


//for sync
static BOOL _bNewSyncMeas = YES;
static NSDate* _dtSyncStart = nil;
static NSDate* _dtLastSync = nil;

static int _nDownloadIdx = 0;
static int _nInitIdx = 0;

static uint8_t _nLastSyncPos = 0;
static int _nLastSyncIdx = 0;
static short _nLastSyncHrate = 0;
static int _nSyncItemCount = 0;
static int _nSyncTotalCount = 0;
static int _nSyncPackIdx = 0;
static BOOL _bSyncSentEndDataToSvr = NO;
static BOOL _bSyncDataError = NO;
static BOOL _bSyncOldVer = NO;

//static NSInteger _nSyncCurtUtc = 0;
static NSUInteger _nSyncStartUtc = 0;
static NSUInteger _nSyncLastUtc = 0;

static BOOL _bSureNew = YES;
static BOOL _bNewFinished = NO;
static NSTimer* _syncTimer = nil;
static BOOL _bSyncException = YES;
static uint8_t _aSyncCheckSum[__nSyncPackCount];
static BOOL _bDownloadMemEnd = NO;

@interface HeaRateViewCtrl ()

@end

@implementation HeaRateViewCtrl {
  BOOL _bDropDownTap;

  UILabel* _lblMsg;
  UIImageView* _ivDropdwon;
  UILabel* _lblDropDownList;
  NIDropDownList* _ddlBleDevice;
  
  BOOL _bChoseBleDev;
    
  UIButton* _btnStartStop;
  UICurveView* _pViewCurve;
    
  UILabel* _lblHrateVal;
  UILabel* _lblElapTimeTip;
  UILabel* _lblElapTimeVal;
  
  UILabel* _lblZoneTip;
    
  UILabel* _lblTotalPtTip;
  UILabel* _lblTotalPtVal;
  
  UILabel* _lblAvgPtMinTip;
  UILabel* _lblAvgPtMinVal;
  
  //Tpp view
  BOOL _bJustStart;
  BOOL _bSyncData;
  BOOL _bSyncDevStop;
    
  UICurveView* _pViewTpp;
  UIButton* _btnSyncTpp;
  UIActivityIndicatorView* _actView;
    
  //bottom
  UIView*  _ivhLine;
  UIView*  _ivvLine1;
  UIView*  _ivvLine2;
    
  //bottom text
  UILabel* _lblAvgHrateTip;
  UILabel* _lblAvgHrateVal;
  UILabel* _lblAvgHrateUnit;
    
  UILabel* _lblMaxHrateTip;
  UILabel* _lblMaxHrateVal;
  UILabel* _lblMaxHrateUnit;

  UILabel* _lblCalBurnTip;
  UILabel* _lblCalBurnVal;
    
  //body info
  NSInteger _nBodyId;
  Byte _nAgeYear;
  float _fBodyWgt;
  short _nHgtMm;
  Byte _nSexNum;
  short _nExeLvl;
    
    //BLE comm
  BOOL _bIsSuptBLe;
  BOOL _bContBleDev;
  BOOL _bStartBleMeas;
  BOOL bTapStop;
    
  short _nLastHrate;
    
  NcitBleDevice* _ncitBleDev;
    
  //meas data
  NSInteger _nHrateId;
  NSInteger _nDownloadMemHrateId;
  NSInteger _nOnlineMeasHrateId;
  
  NSInteger _nPastHrateId;
  H_Rate* _hRate;
  float _fRngLow;
  float _fRngUpp;
  
  float _fCalRngLow;
  float _fCalRngUpp;
    
  int _nCountTick;
  NSTimer* _measTimer;
  
  double _dAvgHrate;
  short _nAvgHrate;
  short _nMaxHrate;
  short _nMinHrate;
  
  NSDate* _dtMeasStart;
  NSDate* _dtMeasEnd;;
    
  NSDate* _dtLast;
  NSDate* _dtMeas;
  //NSDate* _dtLastMem;

  
  //NSArray *_barColors;//for bar
  CGFloat _faHrate[_nDurtBarNumber];
  CGFloat _faHrtHgt[_nDurtBarNumber];
  CGFloat _faHrateMax;
    
  //battery level
  BOOL _bIpad;
  CGFloat _fBatteryLevel;
  UIImageView* _ivBattery;
  UIView* _batteryFill;
  UILabel* _lblBatLevel;
    
  BOOL _bStoredData;
    
  float _afPointCoef[5];
  
  double _dMeasInterval;
  //debug
  UISegmentedControl* _scDataType;
  
  UILabel* _lblStartStop;
  UILabel* _lblSyncData;
  
  //meas point
  NSDate* dtSwitch;
  
  double _dTotalMeasSecond;
  CGFloat _fActivePoints;
  CGFloat _fBurnedVal;
  
  //sync hrate
  NSInteger _nLastIdx;
  //NSInteger _nLastSyncIdx;
  
  //sync with dev
  CBCharacteristic* _pSyncChar;
  
  UIButton* _btnDownShow;
  
  BOOL _bJustSotreHrateMem;
  int _nLastSyncMemHrateId;
  NSMutableArray* _aHrateMemData;
  NSMutableArray* _aHrateItemMemData;
  BOOL _bBleConnException;
  
  //huitaike
  NSMutableArray* m_rateArray;
}

@synthesize m_aHrateMemData = _aHrateMemData;
@synthesize m_aHrateItemMemData = _aHrateItemMemData;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
  _bDropDownTap = NO;
  self.view.backgroundColor = [UIColor whiteColor];//[UIColor colorWithRed:0.128 green:0.128 blue:0.128 alpha:0.5];
    
    [self setBodyMeasInfo];
    
    _bStartBleMeas = NO;
    AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    _ncitBleDev = pApp.m_ncitBleDev;
    _bIsSuptBLe = pApp.m_bSupportBle;
  
  //_bSyncDevStop = !pApp.m_bDownloadHrmMemory;
                                   
    
    //UIImage* iProf = [pApp getImageScale:@"ic-list.png" scale: 0.4];
    //UIBarButtonItem *profButton = [[UIBarButtonItem alloc] initWithImage:iProf style:UIBarButtonItemStylePlain target:self action:@selector(mainAction:)];
    //self.navigationItem.leftBarButtonItem = leftButton;
    //self.navigationItem.rightBarButtonItem = profButton;
    
    CGRect frame = [[UIScreen mainScreen] bounds];
    CGFloat W = frame.size.width;
    CGFloat H = frame.size.height;
    
    CGFloat yPos = (H > 1000)? 75.0f: 75.0f;
    [self initViewCtrls:yPos scrWdt:W scrHgt:H];
    if(H <= 480)
        yPos -= 8;
    [self initBatteryLevelCtrls:yPos iPad:(H > 1000)];
    
    _actView = nil;
    _bSyncData = NO;
    _bJustStart = NO;
    //_nCountTick = 0;
    
    _bStoredData = NO;
    for(int i=0; i<_nDurtBarNumber; i++) {
        _afPointCoef[i] = 1 + i;
    }
  
  _measTimer = nil;
  _dMeasInterval = 0.0;
  
  for(int i=0; i<__nSyncPackCount; i++) {
    _aSyncCheckSum[i] = 0;
  }
  //[_ncitBleDev setConnBleName:@"OTbear-"];
  
  if(_ncitBleDev.bConnBleDev) {
    _ncitBleDev.bleDelegate = self;
    if(isnan(_fBurnedVal))
      _fBurnedVal = 0.0;
  }
  else {
    _nHrateId = 0;
    _nDownloadMemHrateId = 0;
    _nOnlineMeasHrateId = 0;
    
    _nLastHrate = 0;
    _nPastHrateId = 0;
    _hRate = nil;
    _dtLastSync = nil;
    _dtLast = nil;
    _dtMeas = nil;
    //_dtLastMem = nil;
    _dtMeasStart = nil;
    
    _dTotalMeasSecond = 0.0;
    _fActivePoints = 0.0;
    _fBurnedVal = 0.0;
    
    for(int i=0; i<_nDurtBarNumber; i++) {
      _faHrate[i] = 0;
      _faHrtHgt[i] = 0;
    }
  }
  _faHrateMax = 0;
  bTapStop = NO;
  
  dtSwitch = nil;
  _pSyncChar = nil;
  
  yPos = H - 20;
  /*UIImage* iDown = [UIImage imageNamed: @"ic-uarrow.png"];
  _btnDownShow = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  _btnDownShow.frame = CGRectMake((W-38)/2, yPos, 38, 14);
  [_btnDownShow setBackgroundImage:iDown forState:UIControlStateNormal];
  [_btnDownShow addTarget:self action:@selector(tapImgBtnView:) forControlEvents:UIControlEventTouchUpInside];
  [self.view addSubview:_btnDownShow];*/
  
  //[self hideShowBottomCtrls:YES];
  [self setupSwipeGesture];
  
  self.navigationController.interactivePopGestureRecognizer.enabled = YES;
  //self.navigationController.interactivePopGestureRecognizer.delegate = self;
  _bSyncDevStop = NO;
  
  _nLastIdx = 0;
  /*NSUserDefaults *userSetting = [NSUserDefaults standardUserDefaults];
  [userSetting synchronize];
  int nIdx = (int)[userSetting integerForKey:kSync_LastDldIdx];
  if(nIdx > 0)
    [userSetting setInteger:0 forKey:kSync_LastDldIdx];*/
  
  //huitaike
  _bJustSotreHrateMem = NO;
  _nLastSyncMemHrateId = 0;
  if(_aHrateMemData != nil && _aHrateItemMemData != nil) {
    [self insertHrateDataToDatabase];
  }
  else {
    _aHrateMemData = [[NSMutableArray alloc] init];
    _aHrateItemMemData = [[NSMutableArray alloc] init];
  }
  _bBleConnException = NO;

  //huitaike
  [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(heartRateHistiryData:) name:HEARTRATENUMBERHISTORY object:nil];
  //huitaike
}

- (void) hideShowBottomCtrls:(BOOL)bHide
{
  _pViewTpp.hidden = bHide;
  
  _lblAvgHrateTip.hidden = bHide;
  _lblAvgHrateVal.hidden = bHide;
  _lblAvgHrateUnit.hidden = bHide;
  
  _lblMaxHrateTip.hidden = bHide;
  _lblMaxHrateVal.hidden = bHide;
  _lblMaxHrateUnit.hidden = bHide;
  
  _lblCalBurnTip.hidden = bHide;
  _lblCalBurnVal.hidden = bHide;
  
  _ivhLine.hidden = bHide;
  _ivvLine1.hidden = bHide;
  _ivvLine2.hidden = bHide;
}

- (void) initViewCtrls:(CGFloat) yPos scrWdt:(CGFloat) W scrHgt:(CGFloat)H
{
  BOOL bIpad = H > 1000;
  BOOL bWider = W > 320;
  BOOL bIp4s = H <= 480;
  _bIpad = bIpad;
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  
  CGFloat xPos = bWider?30:40;
  _lblMsg = [[UILabel alloc] initWithFrame:CGRectMake(xPos+(bIpad?10:10), yPos-(bIp4s?15:0), W - xPos*2, 25)];
  _lblMsg.textColor = DefaultColor;
  _lblMsg.font = Regular(17);
  _lblMsg.backgroundColor = [UIColor clearColor];
  _lblMsg.textAlignment = NSTextAlignmentCenter; //bIpad? NSTextAlignmentCenter: NSTextAlignmentRight;
  _lblMsg.text = [NSString stringWithFormat:NSLocalizedString(@"Current HRM for %@ %@", nil), pApp.m_bodyInfo.sFirst, pApp.m_bodyInfo.sLast];
  [self.view addSubview:_lblMsg];
    
    UIImage* iDorpDown = [UIImage imageNamed:@"ic-dropdown.png"];
    _ivDropdwon = [[UIImageView alloc] initWithFrame:CGRectMake(12, yPos+(bIp4s?15:30), W-(bIpad?W/2:110)+20, 33)];
    _ivDropdwon.image = iDorpDown;
    [self.view addSubview:_ivDropdwon];
    UITapGestureRecognizer *ivSingleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTapDropDown)];
    ivSingleTap.numberOfTapsRequired = 1;
    [_ivDropdwon setUserInteractionEnabled:YES];
    [_ivDropdwon addGestureRecognizer:ivSingleTap];
    
    
    _lblDropDownList = [[UILabel alloc] initWithFrame:CGRectMake(20, yPos+(bIp4s?19:34), W-(bIpad?W/2:130)+20, 25)];
    _lblDropDownList.textColor = [UIColor grayColor];
    _lblDropDownList.font = [UIFont systemFontOfSize: 16.0];
    _lblDropDownList.backgroundColor = [UIColor clearColor];
    _lblDropDownList.textAlignment = NSTextAlignmentLeft;
    _lblDropDownList.text = NSLocalizedString(@"Tap to choose device", nil);
    [self.view addSubview:_lblDropDownList];
    
    xPos = 15;
  CGFloat fHgt = H * 0.7;
    _ddlBleDevice = [[NIDropDownList alloc] initWithFrame:CGRectMake(xPos, yPos + (bIp4s?42:58), W-(bIpad?W/2:90)-5, fHgt/*, W-(bIp4s?160:120)*/) type:99];
    _ddlBleDevice.delegate = self;

    
    UIImage* iBtn = [[UIImage imageNamed:@"btn-start.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    _btnStartStop = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//    _btnStartStop.frame = CGRectMake(W - (bIpad? 150: 75), yPos - (bIpad?10:(bIp4s?17:2)), bIpad?88: 72, bIpad?88:72);
    _btnStartStop.frame = CGRectMake(W - (bIpad? 150: 75) + 15, yPos+(bIp4s?19:34) - 5, self.view.frame.size.width / 9, self.view.frame.size.width / 9);
    [_btnStartStop setBackgroundImage:iBtn forState:UIControlStateNormal];
    _btnStartStop.contentMode = UIViewContentModeScaleAspectFit;
    [_btnStartStop addTarget:self action:@selector(tapStartStop:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_btnStartStop];
  
  //tips
  CGFloat fTipxPos = _btnStartStop.frame.origin.x;
  CGFloat fTipyPos = _btnStartStop.frame.origin.y;
  _lblStartStop = [[UILabel alloc] initWithFrame:CGRectMake(fTipxPos - ((bIpad)?20:20), fTipyPos + (bIpad?86:70),  bIpad?128:112, 22)];
  _lblStartStop.textColor = DefaultColor;
  _lblStartStop.font = [UIFont systemFontOfSize:16.0];
  _lblStartStop.backgroundColor = [UIColor clearColor];
  _lblStartStop.textAlignment = NSTextAlignmentCenter;
  _lblStartStop.text = @"START";
//  [self.view addSubview:_lblStartStop]; 
    
    _lblHrateVal = [[UILabel alloc] initWithFrame:CGRectMake(5, yPos + (bIp4s?60:80), W/3.0-25, 40)];
    _lblHrateVal.textColor = DefaultColor;
    _lblHrateVal.font = Bold(24);
    _lblHrateVal.backgroundColor = [UIColor clearColor];
    _lblHrateVal.textAlignment = bIpad?NSTextAlignmentRight:NSTextAlignmentCenter;
    _lblHrateVal.text = @"bpm.";
    [self.view addSubview:_lblHrateVal];
    
  _lblElapTimeTip = [[UILabel alloc] initWithFrame:CGRectMake(W/3.0-(bWider?45:35), yPos + (bIp4s?60:80), W/3.0, 40)];
  _lblElapTimeTip.textColor = DefaultColor;
  _lblElapTimeTip.font = Regular(17);
  _lblElapTimeTip.backgroundColor = [UIColor clearColor];
  _lblElapTimeTip.textAlignment = NSTextAlignmentRight;
  _lblElapTimeTip.text = NSLocalizedString(@"Elapsed Time", nil);
  [self.view addSubview:_lblElapTimeTip];
    
  _lblElapTimeVal = [[UILabel alloc] initWithFrame:CGRectMake(W*2.0/3.0-(bWider?38:28), yPos + (bIp4s?60:80), W/3.0, 40)];
  _lblElapTimeVal.textColor = DefaultColor;
  _lblElapTimeVal.font = Bold(24);;
  _lblElapTimeVal.backgroundColor = [UIColor clearColor];
  _lblElapTimeVal.textAlignment = NSTextAlignmentLeft;
  _lblElapTimeVal.text = @"0:00:00";
  [self.view addSubview:_lblElapTimeVal];
  
  //zone tipbIpadΩ
  _lblZoneTip = [[UILabel alloc] initWithFrame:CGRectMake(W-(bIpad?65:58), yPos + (bIp4s?72:92), 50, 25)];
  _lblZoneTip.textAlignment = NSTextAlignmentCenter;
  _lblZoneTip.font = [UIFont systemFontOfSize:14.0];
  _lblZoneTip.textColor = DefaultColor;
  _lblZoneTip.text = NSLocalizedString(@"ZONE", nil);
  //_lblZoneTip.backgroundColor = [UIColor orangeColor];
  [self.view addSubview:_lblZoneTip];
    
  fHgt =  bIpad? (H/2.8):(bWider? H/3.2: H/3.6);
  _pViewCurve = [[UICurveView alloc] initWithFrame:CGRectMake(5, yPos+(bIp4s? 100:120), W-18, fHgt) hBar: YES];
  
  /*short nMaxHrt = 210 - _nAgeYear / 2 - _fBodyWgt * 0.05;
  if(_nSexNum == 1)
    nMaxHrt += 4;
  float nRngLow = nMaxHrt * _FitHR_RngMin;
  float nRngUpp = nMaxHrt * _FitHR_RngMax;
  [_pViewCurve setFitnessHrates:nRngLow maxHrt:nRngUpp];*/
    
  /*short nMaxHrt = [pApp calHrateFitnessRng: NO];
  if(pApp.m_bodyInfo.nMaxBpm != nMaxHrt)
    [_pViewCurve setFitnessHrates:(float)pApp.m_bodyInfo.nMaBpm];
  else
    [_pViewCurve setFitnessHrates:(float)nMaxHrt];*/
  
  _pViewCurve.dataSource = self;
  _pViewCurve.delegate = self;
  [self.view addSubview:_pViewCurve];
    
  //_fRngLow = nRngLow;
  //_fRngUpp = nRngUpp;
    
    //totao point
  _lblTotalPtTip = [[UILabel alloc] initWithFrame:CGRectMake(bIpad?90:12, yPos +fHgt + (bIp4s? 95:125), W/4.0+15, 40)];
    _lblTotalPtTip.textColor = DefaultColor;
    _lblTotalPtTip.font = [UIFont systemFontOfSize: bWider?14.0:12.0];
    _lblTotalPtTip.backgroundColor = [UIColor clearColor];
  _lblTotalPtTip.textAlignment = NSTextAlignmentLeft;//NSTextAlignmentCenter:NSTextAlignmentLeft;
  _lblTotalPtTip.lineBreakMode = NSLineBreakByWordWrapping;
  _lblTotalPtTip.numberOfLines = 2;
    _lblTotalPtTip.text = @"INTENSITY\nPOINTS";//@"Total Intensity";
//    [self.view addSubview:_lblTotalPtTip];
    
  _lblTotalPtVal = [[UILabel alloc] initWithFrame:CGRectMake(W/4.0 + (bIpad?-30:bWider?8:5), yPos + fHgt + (bIp4s? 100:130), W/4.0+5, 40)];
    _lblTotalPtVal.textColor = DefaultColor;
    _lblTotalPtVal.font = [UIFont boldSystemFontOfSize:  bWider?28.0:24.0];
    _lblTotalPtVal.backgroundColor = [UIColor clearColor];
    _lblTotalPtVal.textAlignment = NSTextAlignmentCenter;
    _lblTotalPtVal.text = @"000";
//    [self.view addSubview:_lblTotalPtVal];
    
    //avt point per min
  _lblAvgPtMinTip = [[UILabel alloc] initWithFrame:CGRectMake(W/2.0 + 10, yPos + fHgt + (bIp4s? 100:130), W/4.0+0, 40)];
    _lblAvgPtMinTip.textColor = DefaultColor;
    _lblAvgPtMinTip.font = Regular(14);
    _lblAvgPtMinTip.backgroundColor = [UIColor clearColor];
    _lblAvgPtMinTip.textAlignment = bIpad?NSTextAlignmentRight:NSTextAlignmentCenter;
    _lblAvgPtMinTip.text = NSLocalizedString(@"CALs/Min", nil);
    [self.view addSubview:_lblAvgPtMinTip];
    
    _lblAvgPtMinVal = [[UILabel alloc] initWithFrame:CGRectMake(W*3.0/4.0, yPos + fHgt + (bIp4s? 100:130), W/4.0, 40)];
    _lblAvgPtMinVal.textColor = DefaultColor;
    _lblAvgPtMinVal.font = Bold(24);
    _lblAvgPtMinVal.backgroundColor = [UIColor clearColor];
    _lblAvgPtMinVal.textAlignment = NSTextAlignmentCenter;
    _lblAvgPtMinVal.text = @"0.0";
    [self.view addSubview:_lblAvgPtMinVal];
    
    //tpp view
    fHgt = bIpad? (fHgt * 4.0 / 6.0) : (fHgt * 3.0/ 6.0);
    CGFloat fWid = W - (bIpad? 100: 50);
    yPos += fHgt + (bWider?270: (bIp4s?200:240));
    if (bIp4s)
        fHgt -= 10;
    else if(bIpad)
        yPos += 18;
    else if(H == 736)
        yPos += 20;
        
    _pViewTpp = [[UICurveView alloc] initWithFrame:CGRectMake(12,  yPos, fWid, fHgt) hBar: NO];
    //[_pViewTpp setFitnessHrates:nRngLow maxHrt:nRngUpp];
  //[_pViewTpp setFitnessHrates:(float)nMaxHrt];
    _pViewTpp.dataSource = self;
    _pViewTpp.delegate = self;
    //_pViewTpp.backgroundColor = [UIColor redColor];
    [self.view addSubview:_pViewTpp];
    
    //CGFloat ySyncPos = bWider? 270: 240;
    //if(bIpad)
        //ySyncPos += 105;
    xPos = W - (bIpad? 100: (bIp4s?50:58));
    yPos = yPos + fHgt / 2.0 - (bIpad?28: 20);
    if(bIp4s)
        yPos -= 8;
    iBtn = [[UIImage imageNamed:@"btn-sync-g.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    _btnSyncTpp = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    _btnSyncTpp.frame = CGRectMake(xPos, yPos, bIpad?72:(bIp4s?48:56), bIpad?72:(bIp4s?48:56));
    [_btnSyncTpp setBackgroundImage:iBtn forState:UIControlStateNormal];
    [_btnSyncTpp addTarget:self action:@selector(tapStartStop:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_btnSyncTpp];
    _btnSyncTpp.hidden = YES;
    
    //bottom line and text
    xPos = W - (bIpad? 100: (bIp4s?50:58));
    
    //bottom line and text
    yPos = H * 5.0 / 6.0;
    CGRect rt;
    UIImage* iCon = [[UIImage imageNamed:@"ic-horline.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    fHgt =  iCon.size.height  * 2 / 3; //W * iCon.size.height / iCon.size.width;
    rt.origin.x = 0;
    rt.origin.y =   yPos;
    rt.size.height = 1;
    rt.size.width = W;
    _ivhLine  = [[UIView alloc] initWithFrame:rt];
    _ivhLine.backgroundColor = [UIColor grayColor];
    _ivhLine.alpha = 0.7;
    
    //    [_ivhLine setImage:iCon];
    [self.view addSubview:_ivhLine];
    
    iCon = [[UIImage imageNamed:@"ic-verline.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    fHgt =  iCon.size.width * 2 / 3;
    rt.origin.x = W / 3.0 - fHgt / 2.0;
    rt.origin.y = rt.origin.y + 15;
    //    rt.size.height = H - rt.origin.y - 10;
    rt.size.height = 0.5;
    rt.size.width = fHgt;//iCon.size.width;
    //    _ivvLine1  = [[UIView alloc] initWithFrame:rt];
    _ivvLine1  = [[UIView alloc] initWithFrame:CGRectMake(W / 3, CGRectGetMaxY(_ivhLine.frame), 1.0, 500)];
    _ivvLine1.backgroundColor = [UIColor grayColor];
    _ivvLine1.alpha = 0.7;
    //    [_ivvLine1 setImage:iCon];
    [self.view addSubview:_ivvLine1];
    
    
    rt.origin.x = W * 2.0 / 3.0 - fHgt / 2.0;
    rt.size.height = 1;
    //NSURLSessionConfiguration* cnfgSession = [NSURLSessionConfiguration defaultSessionConfiguration];
    //[NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier: @"HrateSync"];
    _ivvLine2  = [[UIView alloc] initWithFrame:CGRectMake(W / 3 * 2, CGRectGetMaxY(_ivhLine.frame), 1.0, 500)];
    _ivvLine2.backgroundColor = [UIColor grayColor];
    _ivvLine2.alpha = 0.7;
    //  [_ivvLine2 setImage:iCon];
    [self.view addSubview:_ivvLine2];
    
    //text
    fWid = bIpad?  W/6.0-5: W/3.0-5;
    xPos = bIpad? W/20.0 : W/80.0; //5;
    CGFloat fDelata = bIpad? 65:45;
    if(bIp4s)
        fDelata -= 10;
//    _lblAvgHrateTip = [[UILabel alloc] initWithFrame:CGRectMake(xPos,  yPos+(bIp4s?5:15), fWid, 30)];
    _lblAvgHrateTip = [[UILabel alloc] initWithFrame:CGRectMake(xPos,  yPos + fDelata + 15, fWid, 30)];
    _lblAvgHrateTip.textColor = [UIColor blackColor];
    _lblAvgHrateTip.font = [UIFont systemFontOfSize:14.0];
    _lblAvgHrateTip.backgroundColor = [UIColor clearColor];
    _lblAvgHrateTip.textAlignment = NSTextAlignmentCenter;
    _lblAvgHrateTip.text = NSLocalizedString(@"Avg HR", nil);
    _lblAvgHrateTip.lineBreakMode = YES;
    [self.view addSubview:_lblAvgHrateTip];
  
//    _lblAvgHrateVal =[[UILabel alloc] initWithFrame:CGRectMake(xPos,  yPos + fDelata, fWid-30, 40)];
    _lblAvgHrateVal =[[UILabel alloc] initWithFrame:CGRectMake(xPos,  yPos+(bIp4s?5:15), fWid, 40)];
    _lblAvgHrateVal.textColor = DefaultColor;
    _lblAvgHrateVal.font = Bold(H / 34);
    _lblAvgHrateVal.backgroundColor = [UIColor clearColor];
    _lblAvgHrateVal.textAlignment = NSTextAlignmentCenter;
    _lblAvgHrateVal.text = @"--- bpm";
    _lblAvgHrateVal.lineBreakMode = YES;
    [self.view addSubview:_lblAvgHrateVal];
    //_lblAvgHrateVal.backgroundColor = [UIColor blueColor];
    _lblAvgHrateVal.centerX = _lblAvgHrateTip.centerX;
    _lblAvgHrateUnit = [[UILabel alloc] initWithFrame:CGRectMake(xPos + fWid-35,  yPos + fDelata + 12, 30, 20)];
    _lblAvgHrateUnit.textColor = DefaultColor;
    _lblAvgHrateUnit.font = [UIFont boldSystemFontOfSize: 12.6];
    _lblAvgHrateUnit.textAlignment = NSTextAlignmentLeft;
    _lblAvgHrateUnit.text = @"bpm";
    _lblAvgHrateUnit.centerY = _lblAvgHrateVal.centerY;
    _lblAvgHrateUnit.lineBreakMode = YES;
    
//    [self.view addSubview:_lblAvgHrateUnit];
    //_lblAvgHrateUnit.backgroundColor = [UIColor redColor];
    
    
    xPos += W / 3.0;
    _lblMaxHrateTip = [[UILabel alloc] initWithFrame:CGRectMake(xPos, yPos + (bIp4s?5:15), fWid, 30)];
    _lblMaxHrateTip.textColor = [UIColor blackColor];
    _lblMaxHrateTip.font = [UIFont systemFontOfSize:14.0];
    _lblMaxHrateTip.backgroundColor = [UIColor clearColor];
    _lblMaxHrateTip.textAlignment = NSTextAlignmentCenter;
    _lblMaxHrateTip.text = NSLocalizedString(@"Max HR", nil);
    _lblMaxHrateTip.centerY = _lblAvgHrateTip.centerY;
    [self.view addSubview:_lblMaxHrateTip];

    _lblMaxHrateVal = [[UILabel alloc] initWithFrame:CGRectMake(xPos, yPos + fDelata, fWid, 40)];
    _lblMaxHrateVal.textColor = DefaultColor;
    _lblMaxHrateVal.font = Bold(H / 34);
    _lblMaxHrateVal.backgroundColor = [UIColor clearColor];
    _lblMaxHrateVal.textAlignment = NSTextAlignmentCenter;
    _lblMaxHrateVal.text = @"--- bpm";
    _lblMaxHrateVal.centerY = _lblAvgHrateVal.centerY;
    [self.view addSubview:_lblMaxHrateVal];
    _lblMaxHrateVal.centerX = _lblMaxHrateTip.centerX;
    
    _lblMaxHrateUnit = [[UILabel alloc] initWithFrame:CGRectMake(xPos + fWid-35,  yPos + fDelata + 12, 30, 20)];
    _lblMaxHrateUnit.textColor = DefaultColor;
    _lblMaxHrateUnit.font = [UIFont boldSystemFontOfSize: 12.6];
    _lblMaxHrateUnit.backgroundColor = [UIColor clearColor];
    _lblMaxHrateUnit.textAlignment = NSTextAlignmentLeft;
    _lblMaxHrateUnit.text = @"bpm";
    _lblMaxHrateUnit.lineBreakMode = YES;
    _lblMaxHrateUnit.centerY = _lblAvgHrateVal.centerY;
//    [self.view addSubview:_lblMaxHrateUnit];

    xPos += W / 3.0;
    _lblCalBurnTip = [[UILabel alloc] initWithFrame:CGRectMake(xPos, yPos + (bIp4s?5:15), fWid, 30)];
    _lblCalBurnTip.textColor = [UIColor blackColor];
    _lblCalBurnTip.font = [UIFont systemFontOfSize:14.0];
    _lblCalBurnTip.backgroundColor = [UIColor clearColor];
    _lblCalBurnTip.textAlignment = NSTextAlignmentCenter;
    _lblCalBurnTip.text = NSLocalizedString(@"Cals Burned", nil);
    _lblCalBurnTip.centerY = _lblAvgHrateTip.centerY;
    [self.view addSubview:_lblCalBurnTip];
    
    _lblCalBurnVal = [[UILabel alloc] initWithFrame:CGRectMake(xPos, yPos + fDelata, fWid, 40)];
    _lblCalBurnVal.textColor = DefaultColor;
    _lblCalBurnVal.font = Bold(H / 34);
    _lblCalBurnVal.backgroundColor = [UIColor clearColor];
    _lblCalBurnVal.textAlignment = NSTextAlignmentCenter;
    _lblCalBurnVal.centerY = _lblAvgHrateVal.centerY;
    _lblCalBurnVal.text = @"---";
    [self.view addSubview:_lblCalBurnVal];
    
    [self.view addSubview:_ddlBleDevice];
  
  //tips
  fTipxPos = _btnSyncTpp.frame.origin.x;
  fTipyPos = _btnSyncTpp.frame.origin.y;
  _lblSyncData = [[UILabel alloc] initWithFrame:CGRectMake(fTipxPos - 10, fTipyPos + (bIpad?74:(bIp4s?48:56)), bIpad?92:(bIp4s?68:76), 22)];
  _lblSyncData.textColor = DefaultColor;
  _lblSyncData.font = [UIFont systemFontOfSize:16.0];
  _lblSyncData.backgroundColor = [UIColor clearColor];
  _lblSyncData.textAlignment = NSTextAlignmentCenter;
  _lblSyncData.text = @"SYNC";
  [self.view addSubview:_lblSyncData];
  _lblSyncData.hidden = YES;
    
    /*_barColors = @[[[UIColor blueColor] colorWithAlphaComponent:0.5],
                   [[UIColor greenColor] colorWithAlphaComponent:0.5],
                   [[UIColor yellowColor]colorWithAlphaComponent:0.5],
                   [[UIColor orangeColor] colorWithAlphaComponent:0.5],
                   [[UIColor redColor] colorWithAlphaComponent:0.5]];*/
  
  //deubg
  /*_scDataType = [[UISegmentedControl alloc] initWithItems:@[@"ALL", @"Recv/Send", @"Sync Hrate", @"NONE"]];
  _scDataType.frame = CGRectMake((W-300)/2, yPos - (bIpad?305:(bWider?110: 80)), 300, 28);
  _scDataType.tintColor = [UIColor lightGrayColor];

  [_scDataType addTarget:self action:@selector(onDebugDateTypeChg:) forControlEvents:UIControlEventValueChanged];
  _scDataType.selectedSegmentIndex = 1;
  [self.view addSubview:_scDataType];
  _ncitBleDev.nDebugDataType = _scDataType.selectedSegmentIndex;*/
  
  _ncitBleDev.nDebugDataType =3;
}

-(void) showMessage:(NSString*)sMsg
{
  _lblMsg.text = sMsg;
}

- (void) setupSwipeGesture
{
  /*if(self.navigationItem.hidesBackButton) {
    _lblMsg.text = @"Downloading Memory, Please Wait.";
    return;
  }*/
  
  //left swipe
  UISwipeGestureRecognizer* swipeGestureUp= [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipeGesture:)];
  swipeGestureUp.direction = UISwipeGestureRecognizerDirectionUp;// || UISwipeGestureRecognizerDirectionDown®;
  //swipeGestureMove.numberOfTapsRequired = 1; //点击次数
  //swipeGestureMove.numberOfTouchesRequired = 1; //点击手指数
  [self.view addGestureRecognizer:swipeGestureUp];
  
  UISwipeGestureRecognizer* swipeGestureDown = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeGesture:)];
  swipeGestureDown.direction = UISwipeGestureRecognizerDirectionDown; //默认向右
  [self.view addGestureRecognizer:swipeGestureDown];
  
  UISwipeGestureRecognizer* swipeGestureRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(gestureRecognizerShouldBegin:)];
  swipeGestureRight.direction = UISwipeGestureRecognizerDirectionRight; //默认向右
  [self.view addGestureRecognizer:swipeGestureRight];
}

- (void)handleSwipeGesture:(UIGestureRecognizer*)sender {
  /*if(_bSyncData && !_bSyncDevStop) {
    AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [pApp showAlertBox:@"Please Wait" msg:@"Downloading Memory"];
    AudioServicesPlaySystemSound(1112);
    return;
  }*/
  //eWgtAppDelegate *appDelegate = (eWgtAppDelegate *)[[UIApplication sharedApplication] delegate];
  UISwipeGestureRecognizerDirection direction = [(UISwipeGestureRecognizer *)sender direction];
  
  //bool bToUp = direction == UISwipeGestureRecognizerDirectionUp;
  bool bToDown = direction == UISwipeGestureRecognizerDirectionDown;
  
  CATransition* animation = [CATransition animation];
  [animation setDuration:0.5f];
  [animation setType:kCATransitionReveal];
  
 
  [animation setSubtype:(bToDown?kCATransitionFade:kCATransitionMoveIn)];
  [[self.view.superview layer]addAnimation:animation forKey:@"switchHrateBot"];
  
  BOOL bHide = bToDown;
  UIImage* iArrow = [UIImage imageNamed:bHide?@"ic-uarrow.png":@"ic-darrow.png"];
  [_btnDownShow setBackgroundImage:iArrow forState:UIControlStateNormal];
//  [self hideShowBottomCtrls:bHide];
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
   AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  if(self.navigationItem.hidesBackButton) {
    [pApp showAlertBox:NSLocalizedString(@"Please Wait", nil) msg:NSLocalizedString(@"Downloading Memory", nil)];
    AudioServicesPlaySystemSound(1112);
    return NO;
  }
  else {
    [pApp enterMainPage];
    return YES;
  }
}

/*- (void)handleSwipeGestureRight:(UIGestureRecognizer*)sender {
  if(self.navigationItem.hidesBackButton) {
    AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [pApp showAlertBox:@"Please Wait" msg:@"Downloading Memory"];
    return;
  }
  //[self viewWillDisappear:YES];
  //NSString* sIfne = [_btnDownShow.currentBackgroundImage accessibilityIdentifier];
  [self hideShowBottomCtrls:YES];
}*/

-(void) onDebugDateTypeChg:(id)sender
{
  NSUInteger nIdx = _scDataType.selectedSegmentIndex;
  _ncitBleDev.nDebugDataType = nIdx;
  //_lblMsg.text = [NSString stringWithFormat:@"Debug Data Type Chged: %i", (int)nIdx];
}

- (void) initBatteryLevelCtrls:(CGFloat) yPos iPad:(BOOL)bIpad
{
  CGFloat xPos = bIpad?10: 10;
    UIImage* iBkgd = [UIImage imageNamed:@"ic-Battery.png"];
    _ivBattery = [[UIImageView alloc] initWithImage:iBkgd];
    _ivBattery.frame = CGRectMake(xPos, yPos, bIpad?62:40, bIpad?28:20);
    [self.view addSubview:_ivBattery];
    _ivBattery.alpha = 0.75;
    
    /*CGFloat imgyPos = bIpad? (yPos + 160):(yPos + 140);
    CGFloat lblPos = bIpad? imgyPos+135: imgyPos+115;
    if(bIpad) {
        //imgWid *= 1.8;
        //imgHgt *= 1.8;
        //imgxPos = (W-imgWid)/ 2 + 10;
        lblPos += 48;
    }*/
  
  xPos += 2;
    CGFloat fFillWidth = bIpad? kiPadBatteryFillWidth: kBatteryFillWidth;
    _batteryFill = [[UIView alloc] init];
    [_batteryFill setFrame:CGRectMake(xPos, yPos+2, fFillWidth, bIpad?24:16)];
    //[_batteryFill setBackgroundColor:[UIColor greenColor]];
    [[_batteryFill layer] setCornerRadius:4];
    [self.view insertSubview:_batteryFill atIndex:0];
    //[self reloadBatteryLevel];
    
    _lblBatLevel = [[UILabel alloc] initWithFrame:CGRectMake(xPos, yPos, fFillWidth, bIpad?28:20)];
    _lblBatLevel.textAlignment = NSTextAlignmentCenter;//UITextAlignmentRight;
    _lblBatLevel.textColor = DefaultColor; //darkGrayColor
    _lblBatLevel.font = [UIFont boldSystemFontOfSize:bIpad?13.0f:11.0f];
    _lblBatLevel.text = @"";
    [self.view addSubview:_lblBatLevel];
}

- (void) viewWillAppear:(BOOL)animated
{
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:self.view.frame];
    imgView.contentMode = UIViewContentModeScaleAspectFill;
    imgView.image = [UIImage imageNamed:@"ic-mainbkgd2"];
    [self.view insertSubview:imgView atIndex:0];
  _nLastHrate = -1;
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  short nMaxHrt = [pApp calHrateFitnessRng: NO];
  
  _fCalRngLow = nMaxHrt * 0.5;
  _fCalRngUpp = nMaxHrt * 0.7;
  
  
  if(pApp.m_bodyInfo.nMaxBpm != nMaxHrt)
    nMaxHrt = pApp.m_bodyInfo.nMaxBpm;
  
  [_pViewCurve setFitnessHrates:(float)nMaxHrt];
  [_pViewTpp setFitnessHrates:(float)nMaxHrt];

  _fRngLow = nMaxHrt * 0.5;
  _fRngUpp = nMaxHrt * 0.7;
  
  ViewController* rtViewCtrel = pApp.m_pRootViewCtrl;
  if(_ncitBleDev.bConnBleDev) {
    _dAvgHrate = 0.0;
    _nAvgHrate = 0;
    _nMaxHrate = 0;
    _nMinHrate = 1000;
    
    _nCountTick = 1;
    _bContBleDev = YES;
    _bStartBleMeas = YES;
    dtSwitch = [NSDate date];
    
    _bSyncData = NO;
    _ncitBleDev.bSyncDevData = NO;
    UIImage* iBtn = [UIImage imageNamed:@"btn-stop.png"];
    [_btnStartStop setBackgroundImage:iBtn forState:UIControlStateNormal];
    _lblStartStop.text = @"STOP";
    
    //get store rng dur
    CGFloat* aRngDur = [rtViewCtrel getStoreRngDurTime];
    
    _fBatteryLevel = rtViewCtrel.fBatterylvl;
    [self setBatteryLevelWithAnimation:YES forValue:_fBatteryLevel inPercent:YES];
    
    for(int i=0; i<_nDurtBarNumber; i++) {
      _faHrate[i] = aRngDur[i];
      [_pViewTpp setTimeRngDur:i dur:_faHrate[i]];
    }
    _faHrateMax = [self getBarHgtMax];
    //[_pViewCurve setNeedsDisplay];
    [_pViewTpp reloadData];
    
    _lblDropDownList.text = [_ncitBleDev getBlePerName];

  }
  else {
    _nCountTick = 0;
    dtSwitch = nil;
    [_pViewCurve setNeedsDisplay];
    [_pViewTpp setNeedsDisplay];
  }
  
  if(_ncitBleDev.bConnBleDev) {
    _nPastHrateId = rtViewCtrel.nHrateId;
    [self insertPastHrateItem];
  }
}

- (void) tapImgBtnView:(id)sender
{
  //_lblMsg.text = @"Show content";
  BOOL bHide = !_pViewTpp.hidden;
  UIImage* iArrow = [UIImage imageNamed:bHide?@"ic-uarrow.png":@"ic-darrow.png"];
  [_btnDownShow setBackgroundImage:iArrow forState:UIControlStateNormal];
//  [self hideShowBottomCtrls:bHide];
}

- (void) insertPastHrateItem
{
  if(_nPastHrateId == 0)
    return;

  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  NSMutableArray* pHrtItem = [NSMutableArray arrayWithArray:[pApp loadHrateItemData:_nPastHrateId last:NO]];
  if(pHrtItem != nil) {
    NSUInteger nCount = pHrtItem.count;
    for(NSUInteger i= 0; i<nCount; i++) {
      H_RateItem* hItem = [pHrtItem objectAtIndex:i];
      if(hItem == nil)
        continue;
      short nBmp = hItem.hRateValue.shortValue;
      [_pViewCurve updateValues:nBmp];
    }
  }
}

- (void) viewWillDisappear:(BOOL)animated
{
  //_ncitBleDev.bleDelegate = nil;
  if(_syncTimer != nil) {
    [_syncTimer invalidate];
    _syncTimer = nil;
  }
  AppDelegate* pApp = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  ViewController* rtViewCtrel = pApp.m_pRootViewCtrl;
  if(isnan(_fBurnedVal))
    _fBurnedVal = 0.0;
  [rtViewCtrel storeHrmMeasPoint:_nHrateId hrate:_hRate dtStart:_dtMeasStart calry:_fBurnedVal dur:_faHrate avg:_nAvgHrate size:_nDurtBarNumber blvl:_fBatteryLevel];
  
  //[_ncitBleDev stopMeas];
  if(_nHrateId != 0/* && !_ncitBleDev.bConnBleDev*/) {
    if(_hRate != nil) {
      _dtMeas = [NSDate date];
      /*NSDate* dtMeas = _bSyncData?_dtLastSync:_dtMeas;
      AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
      [pApp updHrateStartEndTime:_hRate startTime: nil endTime:dtMeas toSvr:!_bSyncData];*/
      //[self storeRateRngData:YES];
      pApp.m_nHrateId = 0;
      _nHrateId = 0;
      _hRate = nil;
    }
    //[self storeRateRngData:!_bSyncData];
    
    
  }
}

-(void) setHrmMeasPoint:(NSInteger)nHrateId hrate:(H_Rate*)pHrate dtStart:(NSDate*)dtPoint calry:(CGFloat)fCalry dur:(CGFloat*)pfDurHrate size:(short)nCount
{
  if(dtPoint == nil || pHrate  == nil)
    return;
  
  _dtLast = [NSDate date];
  _dtMeas = [NSDate date];
  
  _ncitBleDev.bleDelegate = self;
  
  if(nHrateId != 0)
    _nHrateId = nHrateId;
  _nPastHrateId = nHrateId;
  
  _hRate = pHrate;
  _nCountTick = 1;
  _dtMeasStart = [dtPoint dateByAddingTimeInterval:0.0];
  
  //_fActivePoints = fPoints;
  _fBurnedVal = fCalry;
  for (short i=0; i<nCount; i++) {
    _faHrate[i] = pfDurHrate[i];
    if(_pViewTpp != nil)
      [_pViewTpp setTimeRngDur:i dur:_faHrate[i]];
  }
  
  if(_ncitBleDev.bConnBleDev)
    _lblDropDownList.text = [_ncitBleDev getBlePerName];
  
  if(_pViewTpp != nil)
    [_pViewTpp setNeedsDisplay];
}

- (void)didReceiveMemoryWarning {
  [super didReceiveMemoryWarning];
  // Dispose of any resources that can be recreated.
  _lblMsg.text = NSLocalizedString(@"No enough memory!", nil);
  AudioServicesPlaySystemSound(1112);
}


- (void) onTapDropDown
{
   AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  if(_bSyncData) {
    //_lblMsg.text = @"Downloading Memory, Please Wait!";
    [pApp showAlertBox:NSLocalizedString(@"Please Wait", nil) msg:NSLocalizedString(@"Downloading Memory", nil)];
    AudioServicesPlaySystemSound(1112);

    return;
  }
  
  _bJustStart = NO;
  //_bSyncData = YES;
  _bChoseBleDev = NO;
  _bDropDownTap = YES;
  
  if([_ddlBleDevice isPopup]) {
    //[self stopActindicator:@"Cancel"];
    [_ncitBleDev stopScan];
    [_ddlBleDevice hideDropDownList];
    _lblMsg.text = NSLocalizedString(@"Cancel", nil);
    //_Sacn
    return;
  }
  
    //[_ddlBleDevice setListData: nil curSel:@"0"];
  if(_ncitBleDev.bConnBleDev) {
    [_ncitBleDev stopMeas];
  }
  
  _bIsSuptBLe = pApp.m_bSupportBle;
  if(!_bIsSuptBLe) {
    _lblMsg.text = NSLocalizedString(@"Please turn on your BLE with setting", nil);
    AudioServicesPlaySystemSound(1112);
    return;
  }
  
  _ncitBleDev.bJustScanDev = NO;
  _ncitBleDev.bleDelegate = self;
  [_ncitBleDev startScan:@"180D"];
  //[_ncitBleDev startScan:nil];
  [self performSelector:@selector(delayOpenScanSheet) withObject:nil afterDelay:8.0f];
    
  _lblMsg.text = NSLocalizedString(@"Please wait...", nil);
  _lblDropDownList.text = NSLocalizedString(@"Scan BLE HRM...", nil);
}

- (void) bleMgrDiscover:(CBPeripheral *)aPeripheral
{
    NSString* sBleName = aPeripheral.name;
    if(sBleName == nil)
        return;
  //if([_ncitBleDev getCurtStoredUuid:0].length > 0)
    //return;
  //if(![_ncitBleDev isMemroyHrm4:sBleName])
    //return;
    if(sBleName == nil || ![_ncitBleDev isHrmDevice:sBleName])
      return;
  
    
    //if(_bJustScanGrs50) {
    //int nCount = (int)([_ncitBleDev connBLEDevCount:@"OT"] + [_ncitBleDev connBLEDevCount:@"AC"]);
    NSString * sInfo = [NSString stringWithFormat:@"%@", NSLocalizedString(@"Discovered...", nil)];//, nCount];
    _lblDropDownList.text = sInfo;
    if(!_bContBleDev)
      [self showScanSheet];
    else if(_ddlBleDevice.isPopup)
      [_ddlBleDevice hideDropDownList];
}

- (void) showScanSheet {
  NSString* sStoreUuid = [_ncitBleDev getCurtStoredUuid:0];
  if(!_bDropDownTap && sStoreUuid != nil && sStoreUuid.length > 1)
    return;
  
    //if(_bIsSuptBLe) {
    NSMutableDictionary *dirDevMember = [[NSMutableDictionary alloc] init];
    NSInteger nCount = [_ncitBleDev connBLEDevCount];
    for(NSInteger i=0; i<nCount; i++) {
        CBPeripheral *aPeripheral =[_ncitBleDev listBleDev:i];
        if (aPeripheral == nil) {
            break;
        }
        else {
          NSString* sBleName = aPeripheral.name;
          //if(![sBleName hasPrefix:@"OT"] && ![sBleName hasPrefix:@"AC"] && ![sBleName hasSuffix:@"HRM"] && ![sBleName hasPrefix:@"Smart"] && ![sBleName isEqualToString:@"OTbeat"])
          if(sBleName == nil || ![_ncitBleDev isHrmDevice:sBleName])
            continue;
          
        }
        NSString* sId = aPeripheral.identifier.UUIDString;
        //NSString* sVal = sId;
        NSString* sVal = aPeripheral.name;
        [dirDevMember setValue: sVal forKey:sId];
    }
    [_ddlBleDevice setListData:dirDevMember curSel:@"0"];
    [_ddlBleDevice popupDropDownList];
    //_lblInfo.text = @"PleaseSelect a device";//@"Please do the selection";
    //}
}

- (void) delayOpenScanSheet
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(delayOpenScanSheet) object:nil];
    if(_bChoseBleDev)
        return;
    
    //_lblMeasWgt.text = @"Scan Grs50 End...";
    //if([_ddlBleDevice isPopup])
        //return;
    
    [_ncitBleDev stopScan];
    
    //if(_ncitlLeDev.pBleDevSvr != nil)
    //return;
    if([_ncitBleDev connBLEDevCount] > 0) {
        //[self openScanSheet];
      [self showScanSheet];
      _lblDropDownList.text = NSLocalizedString(@"Scan HRM End...", nil);
      _lblMsg.text = NSLocalizedString(@"Scan HRM End...", nil);
    }
    else {
      //_lblMsg.text = @"Please take your HRM On";
      _lblMsg.text = NSLocalizedString(@"Please take HRM", nil);
      _lblDropDownList.text = NSLocalizedString(@"No BLE HRM On", nil);
      AudioServicesPlaySystemSound(1112);
    }
}

- (void) startConnActindicator:(NSString*)sMsg
{
  if(_actView == nil) {
    //CGRect rt = _btnSyncTpp.frame;
    
    //CGRect frame = [[UIScreen mainScreen] bounds];
    //CGFloat W = frame.size.width;
    //CGFloat H = frame.size.height;
    
    CGRect rt = _lblMsg.frame;
    rt.size.height = rt.size.width = _bIpad?36:28;
    rt.origin.x = _btnStartStop.frame.origin.x + (_btnStartStop.frame.size.width - rt.size.height) / 2;
    rt.origin.y += 30;
    _actView = [[UIActivityIndicatorView alloc] initWithFrame:rt];
    _actView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;//UIActivityIndicatorViewStyleWhiteLarge;
    _actView.hidesWhenStopped = YES;
    [self.view addSubview:_actView];
  }
  _btnStartStop.hidden = YES;
  
  _lblMsg.text = sMsg;
  _btnSyncTpp.hidden = YES;
  _actView.hidden = NO;
  [_actView startAnimating];
}

- (void) stopActindicator:(NSString*)sMsg
{
  if(_actView == nil)
     return;
  [_actView stopAnimating];
  _actView.hidden = YES;
  if(sMsg != nil) {
    //_lblMsg.text = sMsg;
    [self performSelectorInBackground:@selector(showSyncMessage:) withObject:sMsg];
  }
  self.navigationItem.leftBarButtonItem = nil;
  if([sMsg hasPrefix:NSLocalizedString(@"Init & Sync OK", nil)]) {
    UIImage* iBtn = [UIImage imageNamed:@"btn-stop.png"];
    [_btnStartStop setBackgroundImage:iBtn forState:UIControlStateNormal];
    _lblStartStop.text = @"STOP";
      
  }
  else {
    UIImage* iBtn = [UIImage imageNamed:@"btn-start.png"];
    [_btnStartStop setBackgroundImage:iBtn forState:UIControlStateNormal];
    _lblStartStop.text = @"START";
  }
    UIButton *btnBack = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
    [btnBack setImage:[UIImage imageNamed:@"btn-left-w.png"] forState:UIControlStateNormal];//@"btn_back.png"
    [btnBack addTarget:self action:@selector(onRtnMainPage:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem* btniBack = [[UIBarButtonItem alloc] initWithCustomView:btnBack];
    self.navigationItem.leftBarButtonItem = btniBack;
  _btnStartStop.hidden = NO;
}

- (void) onRtnMainPage:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (NSString *) niDropDownDelegateMethod: (NIDropDownList *) sender
{
  _nCountTick = 0;
  _bChoseBleDev = YES;
  _lblMsg.text = NSLocalizedString(@"Begin, waiting...", nil);
  
  if(_ncitBleDev.m_pBleDevPer != nil) {
    _sCurBleConn = @"";
    _ddlBleDevice.sCurConnBLeDev = @"";
    [_ncitBleDev cancelPeripheralConnection];
  }
  if(_sCurrUuId != nil && ![_sCurrUuId isEqualToString:sender.sSelValId]) {
    NSUserDefaults *userSetting = [NSUserDefaults standardUserDefaults];
    [userSetting setInteger:0 forKey: kSync_LastMemDldIdx];
    [userSetting synchronize];
    _nLastIdx = 0;
  }
    
  _sCurrUuId = sender.sSelValId;
  _sCurBleConn = @"";
    
    
  _lblDropDownList.text = sender.sSelText;
    if ([self.delegate respondsToSelector:@selector(getDeviceName:)]) {
        [self.delegate getDeviceName:_lblDropDownList.text];
    }
  [_ddlBleDevice hideDropDownList];
  [self reloadBatteryLevel];
  
  _ncitBleDev.bSyncDevData = YES;
  [_ncitBleDev addSavedDevice:_sCurrUuId tryConn: YES type:0 scan:NO];
  //[_ncitBleDev startMeas:@"180D"];
    
  NSString* sSelDev = sender.sSelText;
  _ncitBleDev.sStoredStepUuid = sSelDev;

  [self performSelectorOnMainThread:@selector(startConnActindicator:) withObject:NSLocalizedString(@"Aquiring Memory Data...", nil) waitUntilDone:NO];
  [self resetCtrlsDate];
  [self resetForSyncData];
  
  return _sCurrUuId;
}

- (void) setBodyMeasInfo/*:(N_GroupInfo*) body*/
{
    AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    LoginBodyInfo* bodyInfo = pApp.m_bodyInfo;
    if(bodyInfo == nil) {
         _nBodyId = 0;
        return;
    }

    _nBodyId = bodyInfo.m_nBodyId;
    _nAgeYear = bodyInfo.nYearAge;
    
    //float fVal = bodyInfo.fBodyWgt;
    //if(bodyInfo.nWgtUn != 0)
        //fVal *= _LbtoKg;
    
    _fBodyWgt = bodyInfo.fBodyWgt;
    if(bodyInfo.nWgtUn == 2)
        _fBodyWgt *= _LbtoKg;
    _nHgtMm = bodyInfo.nHgtMm;
    
    _nSexNum = bodyInfo.nGender;
    _nExeLvl = bodyInfo.nActLvl;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

-(void)mainAction:(id)sender  
{  
    AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [pApp enterPageWithRes:@"bodyProfViewCtrl"];
}

//test
/*static BOOL _bHgtPoint = NO;
static short _nLastRate = 0;
static int _nDrawIdx = 0;
static NSTimer* _drawTimer = nil;
- (void) heartRateDateDraw
{
    NSString* sInfo = [NSString stringWithFormat:@"idx: %i", _nDrawIdx];
    _lblMsg.text = sInfo;
    
    short nRate = 50 + 5 * _nDrawIdx;
    if(!_bHgtPoint)
        _bHgtPoint = nRate > 155;
    else
        _bHgtPoint = !(nRate < 100);
    //[self showPulseData:nRate];
    [self recvedHrateData:nRate];
    
    if(_bHgtPoint) {
        _nDrawIdx = 9;
        _bHgtPoint = NO;
    }
    else {
        _nDrawIdx++;
    }
    
    //_nLastIdx = _nDrawIdx;
    _nLastRate = nRate;
}*/

- (void) resetCtrlsDate
{
  for(int i= 0; i<_nDurtBarNumber; i++) {
    _faHrate[i] = 0;
    _faHrtHgt[i] = 0;
  }
  [_pViewCurve resetData];
  [_pViewTpp resetData];
   _lblElapTimeVal.text = @"0:00:00";
}


/*static BOOL _bHgtPoint = NO;
static short _nLastRate = 0;
static int _nDrawIdx = 0;
static NSTimer* _drawTimer = nil;

- (void) heartRateDateDraw
{
  NSString* sInfo = [NSString stringWithFormat:@"idx: %i", _nDrawIdx];
  _lblMsg.text = sInfo;
  
  short nRate = 55 + 5 * _nDrawIdx;
  if(!_bHgtPoint)
    _bHgtPoint = nRate > 240;
  else
    _bHgtPoint = !(nRate < 80);
  //[self showPulseData:nRate];
  [self recvedHrateData:nRate];
  
  if(_bHgtPoint) {
    _nDrawIdx = 0;
    _bHgtPoint = NO;
  }
  else {
    _nDrawIdx++;
  }
  
  //_nLastIdx = _nDrawIdx;
  _nLastRate = nRate;
}*/

- (void) resetForSyncData
{
  //if(_bSyncDevStop) {
    if(![_ncitBleDev isTestHRMDevice]) {
      AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
      NSString* sHrateId = [NSString stringWithFormat:@"%ld", (long)_nDownloadMemHrateId];
      [pApp updHrateSyncLastIdx: sHrateId lastIdx:0];
      
      NSUserDefaults *userSetting = [NSUserDefaults standardUserDefaults];
      [userSetting setInteger:0 forKey: kSync_LastMemDldIdx];
      [userSetting synchronize];
      _nLastIdx = 0;
    }
  //}
  _bDownloadMemEnd = NO;
  _bSyncDevStop = NO;
  _bSyncData = YES;
  
  _nHrateId = 0;
  _nLastHrate = 0;
  _nPastHrateId = 0;
  _bStoredData = NO;
  //_nInitIdx = 0;
  _nDownloadIdx = 0;
  
  _bJustSotreHrateMem = NO;
  _nLastSyncMemHrateId = 0;
  
  _nSyncPackIdx = 0;
  _nSyncStartUtc = 0;
  _nLastSyncIdx = 0;
  _nLastSyncHrate = 0;
  _nSyncItemCount = 0;
  _nSyncTotalCount = 0;
  _bSyncSentEndDataToSvr = NO;
  _bSyncDataError = NO;
  _nSyncLastUtc = 0;
  
  _bSyncException = YES;
  if(_syncTimer != nil) {
    [_syncTimer invalidate];
    _syncTimer = nil;
  }
}

- (void) tapStartStop:(id)sender
{
  bTapStop = NO;
  //test draw start
  /*if(_nDrawIdx >  1) {
    if(_drawTimer != nil) {
      [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(heartRateDateDraw) object:nil];
      [_drawTimer invalidate];
      _drawTimer = nil; 
    }
    _nDrawIdx = 0;
    _bHgtPoint = NO;
    return;
  }
  _nDrawIdx = 0;
  _drawTimer = [NSTimer scheduledTimerWithTimeInterval:1.00 target:self selector:@selector(heartRateDateDraw) userInfo:nil repeats:YES];
  return;*/

  //test draw end
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  _bIsSuptBLe = pApp.m_bSupportBle;
  /*if (!pApp.m_bSupportBle) {
    _lblMsg.text = @"Sorry, Your Dev not support BLE";
    AudioServicesPlaySystemSound(1112);
    return;
  }*/
    
  if(sender == _btnSyncTpp) {
    _bJustStart = NO;
    //_bSyncData = YES;
    _ncitBleDev.bSyncDevData = YES;
    
      
    if(_ncitBleDev.bConnBleDev) {
      [_ncitBleDev stopMeas];
    }
    _ncitBleDev.bJustScanDev = NO;
    _ncitBleDev.bleDelegate = self;
      
    //[_ncitBleDev startMeas:nil];
    [_ncitBleDev startScan:nil]; //@"FC00";
    [self performSelector:@selector(delayOpenScanSheet) withObject:nil afterDelay:8.0f];
        
    //_lblMsg.text = @"Scan HRM. Waiting...";
    [self performSelectorOnMainThread:@selector(startConnActindicator:) withObject:NSLocalizedString(@"Scan HRM and Sync...", nil) waitUntilDone:NO];
    [self resetCtrlsDate];
    
    AudioServicesPlaySystemSound(1109);
    return;
  }
    
  //_bSyncData = NO;
  if(!_bStartBleMeas) {
    if(!_bIsSuptBLe) {
      _lblMsg.text = NSLocalizedString(@"Please turn on your BLE with setting", nil);
      AudioServicesPlaySystemSound(1112);
      return;
    }
    
    _dAvgHrate = 0.0;
    _nAvgHrate = 0;
    _nMaxHrate = 0;
    _nMinHrate = 1000;
    _fBurnedVal = 0.0;
    
    _nCountTick = 0;
    _bContBleDev = NO;
        
    _bStoredData = NO;
    _fBatteryLevel = 0;
      
    //_bSyncData = YES;
    _bJustStart = YES;
    _ncitBleDev.bSyncDevData = YES;//NO;
    _bSyncException = YES;
      
    _ncitBleDev.bJustScanDev = NO;
    _ncitBleDev.bleDelegate = self;
    
    [self resetCtrlsDate];
    [self resetForSyncData];
    _lblMsg.text = NSLocalizedString(@"Pairing to HRM...", nil);//@"Try to connected HRM";
        
    if(_ncitBleDev != nil) {
      if(_ncitBleDev.bConnBleDev) {
        [_ncitBleDev stopMeas];
      }
      _hRate = nil;
    }
        
    [self reloadBatteryLevel];
    _measTimer = [NSTimer scheduledTimerWithTimeInterval:12.0 target:self selector:@selector(onMeasTimer) userInfo:nil repeats:NO];
    //_bStartBleMeas = YES;
    [self performSelectorOnMainThread:@selector(startConnActindicator:) withObject:NSLocalizedString(@"Scan HRM and Sync...", nil) waitUntilDone:NO];
      
    NSString* sStoredUuid = [_ncitBleDev getCurtStoredUuid:0];
    //if([_ncitBleDev loadSavedDevice: 0]) {
    if(sStoredUuid != nil && sStoredUuid.length > 0) {
      [_ddlBleDevice hideDropDownList];
      [_ncitBleDev addSavedDevice:sStoredUuid tryConn:YES type:0 scan:YES];
      //[_ncitBleDev addSavedDevice:sStoredUuid tryConn:YES type:0 scan:NO];
       
      AudioServicesPlaySystemSound(1109);
      return;
    }
        
    [self onTapDropDown];
    [self performSelector:@selector(delayOpenScanSheet) withObject:nil afterDelay:8.0f];
    AudioServicesPlaySystemSound(1109);
    //return;
        
        
    //test start
    /*_measTimer = [NSTimer scheduledTimerWithTimeInterval:1.00 target:self selector:@selector(onMeasTimer) userInfo:nil repeats:YES];
    [self bleDevConnected];
    return;*/
    //test end
        
    /*if(!_bIsSuptBLe) {
            
      UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"BLE Support？" message: @"Maybe your iOS device not support BLE..." delegate:self cancelButtonTitle:NSLocalizedString(@"OK", nil) otherButtonTitles:nil];
      [alertView show];
      _lblMsg.text = NSLocalizedString(@"Device BLE Support?", nil);
      _lblMsg.textColor = [UIColor redColor];
      AudioServicesPlaySystemSound(1112);
      return;
    }
        
    if(_nBodyId == 0) {
      _lblMsg.text = @"No login, No function";//[NSString stringWithFormat:@"%@?", NSLocalizedString(@"RegTips", nil)];//@"At home?";
      _lblMsg.textColor = [UIColor redColor];
      AudioServicesPlaySystemSound(1112);
      return;
    }*/
        
    //[_vBldPres startMeas];
        
    //rem for test and debug
    //[self setBatteryLevelWithAnimation:YES forValue:0.0 inPercent:YES];
    //_lblUnit.text = @"bpp";
  }
  else {
    //_bSyncData = NO;
       
    if(_measTimer != nil) {
      [_measTimer invalidate];
      _measTimer = nil;
    }
  
        
    [_ncitBleDev stopScan];
    [_ncitBleDev stopMeas];
        
    if(_measTimer != nil)
      [_measTimer invalidate];
        
        //store last one
    if(_nHrateId != 0 && _nLastHrate != 0) {
      if(_hRate != nil) {
        _dtMeas = [NSDate date];
        NSDate * dtMeas = _bSyncData?_dtLastSync:_dtMeas;
        if(dtMeas != nil) {
          [pApp updHrateStartEndTime:_hRate startTime:nil endTime:dtMeas toSvr:!_bSyncData];
          [pApp insertHrateItemData:_nHrateId bodyId:_nBodyId hRate:_nLastHrate dtime:dtMeas toSvr:!_bSyncData];
        }
        _nHrateId = 0;
        _hRate = nil;
        pApp.m_nHrateId = 0;
        if(_bSyncData)
          _dtLastSync = nil;
      }
      [self storeRateRngData: !_bSyncData];
      //if(pApp.m_bHostConn)
        //[pApp CloseScaleHost];
    }
    _lblMsg.text = NSLocalizedString(@"Stop HRM", nil);
    _bStartBleMeas = NO;
    bTapStop = YES;
  }
}

- (void) onMeasTimer
{
  if(_ncitBleDev.bConnBleDev || _bSyncData) {
    return;
  }
  
  _bDropDownTap = NO;

  NSString* sMsg = @"";
  AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  if(!_ddlBleDevice.isPopup && !_bContBleDev && !bTapStop) {
    _bDownloadMemEnd = NO;
    sMsg = (pApp.m_bSupportBle)? NSLocalizedString(@"No HRM On, Tap DDL.", nil): nil;
    /*if(_actView.isAnimating)
      [_actView stopAnimating];
    _btnStartStop.hidden = NO;*/
    
    //NSString* sHrateId = [NSString stringWithFormat:@"%ld", (long)_nDownloadMemHrateId];
    //[pApp updHrateSyncLastIdx: sHrateId lastIdx:_nSyncPackIdx];
    
    AudioServicesPlaySystemSound(1112);
  }
  else {
    NSString* sBleName = [_ncitBleDev getBlePerName];
    if(_bStartBleMeas && !_bContBleDev && ![sBleName hasPrefix:@"Smart"] && ![sBleName isEqualToString:@"OTbeat"]) {
      _bDownloadMemEnd = NO;
      _lblMsg.text = NSLocalizedString(@"No HRM On, Tap DDL.", nil);
      AudioServicesPlaySystemSound(1112);
    }
    //make heart rate meas force
    if(_pSyncChar != nil) {
      _pSyncChar = nil;
      
      if(!_bJustSotreHrateMem)
        _bSyncData = NO;
      /*_actView.hidden = YES;
      [_actView stopAnimating];
      _btnStartStop.hidden = NO;*/
    }
  }
  
  if(_measTimer != nil) {
    [_measTimer invalidate];
    _measTimer = nil;
  }
  
  [_ncitBleDev stopScan];
  [self stopActindicator:sMsg];
  //_btnStartStop.hidden = NO;
}

-(void) onSyncTimer
{
  _bDropDownTap = NO;
  
    if(_bSyncData && _nLastSyncIdx == 0) {
      //[_ncitBleDev stopMeas];
      _bSyncException = YES;
      _lblMsg.text = NSLocalizedString(@"Time out! may be no stored data", nil);
      //_btnSyncTpp.hidden = NO;
      [self endSyncProc:0 char:nil hRate:0];
    }
  
  //NSString* sUuid = [_ncitBleDev getBlePerName];
  //if(_bSyncOldVer && ([sUuid hasPrefix:@"Smart"] || [sUuid isEqualToString:@"OTbeat"])) {
  if(_bSyncOldVer && ![_ncitBleDev isMemroyHrmDev]) {
    [_ncitBleDev enabHratNotification];
  }
  
  [_syncTimer invalidate];
  _syncTimer = nil;
}


//BLE deletegate
//interface send data to scale

//ble protocal
/*- (void) bleSupport:(BOOL)bSupport
{
    if(!bSupport) {
        _lblMsg.text = @"BLE Support?";
    }
    _bIsSuptBLe = bSupport;
}*/

- (void) bleDevConnected
{
  _bBleConnException = NO;
  _nDownloadMemHrateId = 0;
  _dAvgHrate = 0.0;
  _nAvgHrate = 0;
  _nMaxHrate = 0;
  _nMinHrate = 1000;
  _fBurnedVal = 0.0;
  
  _nSyncLastUtc = 0;
  _nCountTick = 0;
  _dMeasInterval = 0;
  _bContBleDev = YES;
  _bStartBleMeas = YES;
  _bDropDownTap = NO;
    
  //[_ncitBleDev enableSyncChar:_ncitBleDev.pBleDevChar enable:!_ncitBleDev.bSyncDevData];
  //[_ncitBleDev enableSyncChar:_ncitBleDev.pBleSyncChar enable:_ncitBleDev.bSyncDevData];
    
    _lblMsg.text = NSLocalizedString(@"BLE HRM Connected", nil);//[NSString stringWithFormat: @"%@ %s", [aPeripheral name], "Connected"];
    
    _dtMeasStart = [NSDate date];
    _dtLast = [NSDate date];
    _dtMeas = [NSDate date];
    
    _btnSyncTpp.hidden = YES;
    
    if(_ddlBleDevice.isPopup)
        [_ddlBleDevice hideDropDownList];
    
    if(_bSyncData) {
      _bNewSyncMeas = NO;
      _dtSyncStart = nil;
      _dtLastSync = nil;
      _bSyncDataError = NO;
      _nSyncLastUtc = 0;
      
      _lblMsg.text = NSLocalizedString(@"Aquiring Memory Data...", nil);
      _actView.hidden = NO;
      [_actView startAnimating];
    }
  
  UIImage* iBtn = [UIImage imageNamed:@"btn-stop.png"];
    _btnStartStop.imageView.contentMode = UIViewContentModeScaleAspectFit;
  [_btnStartStop setBackgroundImage:iBtn forState:UIControlStateNormal];
  
  NSString*  sUuid = [_ncitBleDev getBlePerName];
  if(![_ncitBleDev isMemroyHrm4:sUuid])
    _lblStartStop.text = @"STOP";
  
  for(int i=0; i<__nSyncPackCount; i++) {
    _aSyncCheckSum[i] = 0;
  }
  
  _lblHrateVal.text = @"--";
  
  //for old ver HM
  _bSyncOldVer = YES;
  if(_bSyncOldVer) {
    //if(!_bSyncData)
      _bSyncData = [_ncitBleDev isMemroyHrm4:sUuid];
    _syncTimer = [NSTimer scheduledTimerWithTimeInterval:25.00 target:self selector:@selector(onSyncTimer) userInfo:nil repeats:NO];
  }
  //add uuid
  //NSString* sUuid = _lblDropDownList.text;
  _lblDropDownList.text = sUuid;
  
  _bStoredData = NO;
  //if(!_bSyncData && !_bStoredData)
    //[self insertStartHRMData:[NSDate date]];
  
//  if(_bSyncData) {
    self.navigationItem.hidesBackButton = YES;
    //self.navigationController.interactivePopGestureRecognizer.enabled = NO;
//  }
}

- (void) bleDevNoSyncFunc
{
  _bSyncData = NO;
  _actView.hidden = YES;
  [_actView stopAnimating];
  _btnStartStop.hidden = NO;
  
  _dtMeas = [NSDate date];
  _bSureNew = YES;
  //_hRate = nil;
  _bStoredData = NO;
  
  [self insertStartHRMData:_dtMeas];
  
  _lblMsg.text = NSLocalizedString(@"BLE HM Connected", nil);
}
/*- (void) bleDevConnected:(NSString*)sUuid
{
  _lblMsg.text = sUuid;
}*/

#pragma mark - Battery level set
- (void) setBatteryLevelWithAnimation:(BOOL)isAnimated forValue:(CGFloat)batteryLevel inPercent:(BOOL)inPercent {
    
    CGFloat newBatteryLevel = (inPercent) ? batteryLevel : batteryLevel * 100;
    CGFloat newWidth =  (_bIpad?kiPadOnePercent:kOnePercent) * newBatteryLevel + 0.1;
    // Set the new width
    // If animated proceed with the animation
    // else assign the value without animates
    if (isAnimated)
        [UIView animateWithDuration:0.6 animations: ^{
            // This direct assignment is possible
            //using the UIView+ALQuickFrame category
            //http://github.com/andrealufino/ALQuickFrame
            
            _batteryFill.width = newWidth;
            // Set the color based on battery level
            _batteryFill.backgroundColor = [self setColorBasedOnBatteryLevel:newBatteryLevel];
        }];
    else {
        _batteryFill.width = newWidth;
    }
    
    if(batteryLevel < 0.0) {
        //_lblInfo.text = @"Tap one HRM...";
        _lblBatLevel.text = @"";
    }
    else if(batteryLevel < 0.1) {
        //_lblInfo.text = NSLocalizedString(@"Wait.", nil);//@"Waiting...";
        _lblBatLevel.text = @"";
    }
    else {
        //_lblInfo.text = [NSString stringWithFormat:@"Battery Level is: %.0f %%",  batteryLevel];
        _lblBatLevel.text = [NSString stringWithFormat:@"%.0f%%",  batteryLevel];
    }
}

- (void) reloadBatteryLevel {
  _fBatteryLevel = 0.0f;
    // Reset the width of the fill view
    _batteryFill.width = 0.0f;
    // Set the fill of the view to redo the animation
    [self setBatteryLevelWithAnimation:YES forValue:_fBatteryLevel inPercent:YES];
}

- (void) updateBatteryLevel:(short)nLevel
{
    //if(_bSyncData)
        //return;
    
    //_nBarNumber = 1;
    _fBatteryLevel = (CGFloat)nLevel;
    [self setBatteryLevelWithAnimation:YES forValue:_fBatteryLevel inPercent:YES];
    
    //AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    //N_GroupInfo* body = [pApp getBodyObject:_sBodyId];
    //[self setBodyMeasInfo:body];

    
    //conn svr
    //appDelegate CloseScaleHost];
    /*if(!pApp.m_bHostConn)
        [pApp ConnScaleHost:YES IpAddr: NULL Port:_Host_Port];
    
    _btnTurnoff.enabled = YES;*/
  _bContBleDev = YES;
  //_lblHrateVal.text = @"--";
}

- (BOOL) insertStartHRMData:(NSDate*)dtMeas
{
  BOOL bSureNew = _bSureNew;
  if(_bStoredData || _hRate != nil)
    return NO;
  
  _nDownloadMemHrateId = 0;
  _bSyncDevStop = NO;
  BOOL bInserRcd = YES;
  int nIdxDelta = 0;
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  
  //NSInteger nHrateId = _nHrateId;
  _hRate = [pApp insertHrateData:bSureNew bodyId: _nBodyId hrateId:&_nHrateId time:dtMeas toSvr:!_bSyncData];
  //_bStoredData = YES;
  _nInitIdx = 0;
 
  if(_bSyncData && _hRate != nil && _nHrateId >= 0) { // exists
    bInserRcd = NO;
    [pApp refreshCoreDataItems:_hRate];
    //int n = 1;
    _nInitIdx = (int)_hRate.nLastUpdIdx.integerValue;
    if(_nHrateId == 1) {
      NSDate* dtBegin = _hRate.hEnterDate;
      NSTimeInterval dtDelta = [dtMeas timeIntervalSinceDate:dtBegin];
      nIdxDelta = (int)(dtDelta / 120);
      
      if(_nInitIdx != -3 && _nInitIdx != -1 && _nInitIdx <= 0) {
        NSUserDefaults *userSetting = [NSUserDefaults standardUserDefaults];
        _nInitIdx = (int)[userSetting integerForKey:kSync_LastMemDldIdx];
        if(_nInitIdx == -3) {
          [userSetting setInteger:-1 forKey:kSync_LastMemDldIdx];
          _nInitIdx = 0;
        }
        else if(_nInitIdx == -1) {
           _nInitIdx = 0;
        }
      }

      
      /*if(nIdxDelta > 0) {
        if(_nInitIdx >= nIdxDelta)
          _nInitIdx -= nIdxDelta;
        else if(_nInitIdx <= 0)
          _nInitIdx = 0;
      }*/
    }
    else if(_nHrateId == 0) {
      if(_nInitIdx != -3 && _nInitIdx != -1 &&  _nInitIdx <= 0) {
        NSUserDefaults *userSetting = [NSUserDefaults standardUserDefaults];
        _nInitIdx = (int)[userSetting integerForKey:kSync_LastMemDldIdx];
        if(_nInitIdx == -3) {
          [userSetting setInteger:-1 forKey:kSync_LastMemDldIdx];
          _nInitIdx = 0;
        }
        else if(_nInitIdx == -1) {
          _nInitIdx = 0;
        }
      }
    }
    
    if(_nInitIdx < 0) {
      if((_nInitIdx == -3 || _nInitIdx == -1) && [_ncitBleDev isTestHRMDevice]) {
        _bSyncDevStop = YES;
      }
      else {
        //_nInitIdx = 0;
        _bSyncDevStop = NO;
      }
    }
    else {
      _bSyncDevStop = NO;
    }
    _nHrateId = _hRate.hRateId.integerValue;
  }
  else if(_hRate != nil) {
    _nInitIdx = (int)_hRate.nLastUpdIdx.integerValue;
    if(_nInitIdx != -3 && _nInitIdx != -1) {
      NSUserDefaults *userSetting = [NSUserDefaults standardUserDefaults];
      _nInitIdx = (int)[userSetting integerForKey:kSync_LastMemDldIdx];
    }
    
    NSInteger nHrateId = _hRate.hRateId.integerValue;
    if(_bSyncData)
      _nDownloadMemHrateId = nHrateId;
    else
      _nOnlineMeasHrateId = nHrateId;
    _nHrateId = _hRate.hRateId.integerValue;
  }
  //test
  //NSInteger nHrateId = _nHrateId;
  //NSInteger nInitIdx = _nInitIdx;
  //test
  
  if(_hRate != nil) {
    if(_bSyncData)
      _nDownloadMemHrateId = _nHrateId;
    else
      _nOnlineMeasHrateId = _nHrateId;
  }
 
  if(_bSyncData) {
    _nSyncPackIdx = _nInitIdx;
    
    /*NSUserDefaults *userSetting = [NSUserDefaults standardUserDefaults];
    int nIdx = (int)[userSetting integerForKey:kSync_LastDldIdx];
    if(_nInitIdx != -3 && _nInitIdx != -1 && nIdx < _nLastIdx)
      nIdx = (int)_nLastIdx;
    
    if(_nInitIdx != -3 && _nInitIdx != -1  && _nSyncPackIdx < nIdx) {
      _nSyncPackIdx = nIdx;
      _nInitIdx = nIdx;
    }
    
    if(nIdxDelta != 0) {
      if(_nInitIdx >= nIdxDelta)
        _nInitIdx -= nIdxDelta;
      else
        _nInitIdx = 0;
    }
    
    if(nIdx == -3)
      _bSyncDevStop = YES;
    else */
  }
  
  if(_bSyncData && (_nInitIdx == -3 || _nInitIdx == -1)) {
    if([_ncitBleDev isTestHRMDevice]) {
      _bSyncDevStop = YES;
    }
    else {
    _bSyncDevStop = NO;
    _nInitIdx = 0;
    }
  }
  else if(_bSyncDevStop) {
    _bSyncDevStop = NO;
  }
  //for baakground exits
  if(!_bSyncData) {
    pApp.m_pHrate = _hRate;
    pApp.m_nHrateId = _nHrateId;
  }
  //if(_hRate == nil)
    //_bSyncData = NO;
  else if(_bSyncDevStop && _hRate.hRateId.integerValue > 0)
    _nOnlineMeasHrateId = _hRate.hRateId.integerValue;
  
  if(bInserRcd)
    AudioServicesPlaySystemSound(1109);
  
  _bNewFinished = bInserRcd;
  return bInserRcd;
}

/*- (void) recvSyncHrateData:(NSNumber*)hRate
{
  short nHr = hRate.shortValue;
  [self recvedHrateData:nHr];
}*/

- (void) recvedHrateData:(short)nHrate
{
  _bSyncData = NO;
  //_dtMeas = [NSDate date];
  
  if(_actView.isAnimating)
    [_actView stopAnimating];
  
  if(_lblMsg.text.length > 0) {
    _lblMsg.text  = @"";
  }
  
  if(_bSyncData) {
    _nCountTick++;
    _dtLast = [_dtMeas dateByAddingTimeInterval:0];
    _dtMeas = [_dtLastSync dateByAddingTimeInterval:0];
  }
  else {
    if(_nCountTick == 0) {
      if(_dtMeasStart == nil)
        _dtMeasStart = [NSDate date];
      //_dtMeasStart = [NSDate date];
      self.navigationItem.hidesBackButton = NO;
      self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }
    
    //nHrate = 90;
    _nCountTick++;
    if(_dtMeas != nil)
      _dtLast = [_dtMeas dateByAddingTimeInterval:0];
    _dtMeas = [NSDate date];
  }
  if(dtSwitch != nil)
    _dMeasInterval = [_dtMeas timeIntervalSinceDate:dtSwitch] / _nCountTick;
  else
    _dMeasInterval = [_dtMeas timeIntervalSinceDate:_dtMeasStart] / _nCountTick;
    
  [self showPulseData:nHrate upd:YES];
    
  double dTotalScds = [self setHrateOviewData:nHrate];
  [self calDisplayBurnedVal:nHrate];
    
  int nIdx = [_pViewTpp getHrateRngIdx:nHrate];
  if(nIdx > 0 && _dtLast != nil) {
    double dDecDur = [_dtMeas timeIntervalSinceDate:_dtLast];
    _faHrate[nIdx-1] += dDecDur;
    [_pViewTpp setTimeRngDur:nIdx-1 dur:_faHrate[nIdx-1]];
    _faHrateMax = [self getBarHgtMax];
    [_pViewTpp setNeedsDisplay];
    [_pViewTpp reloadData];
    //_fActivePoints += _afPointCoef[nIdx] * dDecDur / 60;
  }
  _fActivePoints = 0.0f;
  for(int i=0; i<_nDurtBarNumber; i++) {
      _fActivePoints += _faHrate[i] * _afPointCoef[i] / 60;
  }
    
  if(_fActivePoints >= 100)
      _lblTotalPtVal.text = [NSString stringWithFormat:@"%.1f", _fActivePoints];
  else
      _lblTotalPtVal.text = [NSString stringWithFormat:@"%.2f", _fActivePoints];
  if(_fBurnedVal > 0) {
    float fCalMin = _fBurnedVal;
    if(fCalMin > 1000)
      fCalMin /= 1000.0;
    if(dTotalScds > 0)
      fCalMin = _fBurnedVal * 60 / dTotalScds;
    else
      fCalMin = 0;
    _lblAvgPtMinVal.text = [NSString stringWithFormat:@"%.2f", fCalMin];
  }
    
  if(_ddlBleDevice.isPopup)
    [_ddlBleDevice hideDropDownList];
}

- (void) addHrateSyncVal:(short)nHrate
{
  _nCountTick++;
  _dtLast = [_dtMeas dateByAddingTimeInterval:0];
  _dtMeas = [_dtLastSync dateByAddingTimeInterval:0];
  [_pViewCurve addHrmMeasVal:nHrate];
  
  _dMeasInterval = [_dtMeas timeIntervalSinceDate:_dtMeasStart] / _nCountTick;
  
  [self showPulseData:nHrate upd:NO];
  double dTotalScds = [self setHrateOviewData:nHrate];
  [self calDisplayBurnedVal:nHrate];
  
  int nIdx = [_pViewTpp getHrateRngIdx:nHrate];
  if(nIdx > 0 && _dtLast != nil) {
    double dDecDur = [_dtMeas timeIntervalSinceDate:_dtLast];
    _faHrate[nIdx-1] += dDecDur;
    [_pViewTpp setTimeRngDur:nIdx-1 dur:_faHrate[nIdx-1]];
    //[_pViewTpp reloadData];
  }
  _fActivePoints = 0.0f;
  for(int i=0; i<_nDurtBarNumber; i++) {
    _fActivePoints += _faHrate[i] * _afPointCoef[i] / 60;
  }
  
  if(_fActivePoints >= 100)
    _lblTotalPtVal.text = [NSString stringWithFormat:@"%.1f", _fActivePoints];
  else
    _lblTotalPtVal.text = [NSString stringWithFormat:@"%.2f", _fActivePoints];
  if(dTotalScds > 0) {
    float fPointMin = _fActivePoints * 60 / dTotalScds;
    _lblAvgPtMinVal.text = [NSString stringWithFormat:@"%.2f", fPointMin];
  }
}


#pragma mark - Private method
// Returns an UIColor object based on the passed battery level
- (UIColor *)setColorBasedOnBatteryLevel:(CGFloat)batteryLevel {
    UIColor *backgroundColor;
    if (batteryLevel <= 20)
        backgroundColor = [UIColor redColor];
    if (batteryLevel > 20 && batteryLevel <= 30)
        backgroundColor = [UIColor blueColor];
    if (batteryLevel > 30)
        backgroundColor = [UIColor greenColor];
    return backgroundColor;
}
//batery level end

- (BOOL) showPulseData:(short)nBpm upd:(BOOL)bUpd
{
  if(nBpm < 30)
      return NO;
    
  NSString* sRecv = [NSString stringWithFormat:@"%d", nBpm];
  [UIView animateWithDuration:0.5 animations:^{
    _lblHrateVal.alpha = 0.0f;
    _lblHrateVal.text = sRecv;
    _lblHrateVal.alpha = 1.0f;
  }];
  if(bUpd) {
    AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [_pViewCurve updateValues:nBpm];
    if(_hRate != nil) {
      if(_dtMeas != nil)
        [pApp updHrateStartEndTime:_hRate startTime:nil endTime:_dtMeas toSvr:YES];
      if(_nOnlineMeasHrateId != 0 && _dtMeas != nil)
        [pApp insertHrateItemData:_nOnlineMeasHrateId bodyId:_nBodyId hRate:nBpm dtime: _dtMeas toSvr: YES];
    }
  }
  
  //send to server start
  /*AppDelegate *appDelegate = (eWgtAppDelegate *)[[UIApplication sharedApplication] delegate];
  BOOL bResolved = appDelegate.m_bHostConn;
  if(!bResolved)
      bResolved = [appDelegate ConnScaleHost:YES IpAddr: NULL Port:_Host_Port];
    
  if(bResolved) {
      NSString* sMsg = [NSString stringWithFormat:@"22;2 ON-HRATE:%@ %@\r\n", _sCurTagId, sRecv];
        appDelegate.socketHost sendData:(char*)[sMsg UTF8String] Alert:NO];
  }*/
  //send to server end
    
  /*CGFloat fAlpha = _imgHeart.alpha;
  fAlpha = (fAlpha == 0.25)? 0.125: 0.25;
  _imgHeart.alpha = fAlpha;*/
    
  return YES;
}

- (double) setHrateOviewData:(short)nHrate
{
    if(_dtMeas == nil || _dtMeasStart == nil)
        return 0.0;
  
  if(_dtMeas == nil && _dtMeasStart != nil)
    _dtMeas = _dtMeasStart;
    //if(nHrate > _pViewCurve.m_yMax || nHrate < _pViewCurve.m_yMin)
        //return  0.0;
    
    if(nHrate > _nMaxHrate)
        _nMaxHrate = nHrate;
    if(nHrate < _nMinHrate)
        _nMinHrate = nHrate;
    
  AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  double dTotalSecond = [_dtMeas timeIntervalSinceDate:_dtMeasStart];
  _lblElapTimeVal.text = [pApp getHourMinSec:dTotalSecond]; // + (_bSyncData?2:0)];
  _dTotalMeasSecond = dTotalSecond;
    
  double dDurSeconds = [_dtMeas timeIntervalSinceDate:_dtLast];
  dTotalSecond -= dDurSeconds;
    
  if(_nAvgHrate == 0) {
    _dAvgHrate = nHrate;
    _nAvgHrate = nHrate;
  }
  else {
    _dAvgHrate = (_dAvgHrate * dTotalSecond + nHrate * dDurSeconds) / (dTotalSecond + dDurSeconds);
  }
  _nAvgHrate = (short)(_dAvgHrate + 0.5);
  
  _lblAvgHrateVal.text = [NSString stringWithFormat:@"%d bmp", (short)(_nAvgHrate)];
  _lblMaxHrateVal.text = [NSString stringWithFormat:@"%d bmp", _nMaxHrate];
  
  pApp.m_nLastHrate = nHrate;
  pApp.m_nCurtAvgHrt = (short)(_nAvgHrate+0.5);
    
  return _dTotalMeasSecond;
}

- (CGFloat) calBurnedCalories:(short) nHrate second:(double)dSec wgt:(double)dWgt age:(short)nAge sex:(short)nSex
{
  CGFloat fCalories = 0.0;
  if(nSex == 1) { //man
    fCalories = ((0.2017 * nAge + 0.1988 * dWgt + 0.6309 * nHrate - 55.0969) / 4.184) * (dSec / 60.0) / 1000.0;
  }
  else { //woman
    fCalories = ((0.074 * nAge - 0.1263 * dWgt + 0.4472 * nHrate - 20.4022) / 4.184) * (dSec / 60.0) / 1000.0;
  }
  fCalories *= 0.5;
  
  if(fCalories < 0)
    fCalories = 0;
  return fCalories;
}

- (void) calDisplayBurnedVal:(short)nRate
{
    if(_dtMeas == nil)
        _dtMeas = [NSDate date];
    
    //NSDate* dt = [NSDate date];
    //double dDurSeconds = [dt timeIntervalSinceDate:_dtMeas];
    double dDurSeconds = [_dtMeas timeIntervalSinceDate:_dtLast];
    //_lblAvgPtMinVal.text = [NSString stringWithFormat:@"%.1f", 60.0 / dDurSeconds];
    
    short nMaxHrt = 210 - _nAgeYear / 2 - _fBodyWgt * 0.05;
    if(_nSexNum == 1)
        nMaxHrt += 4;
    //short nRngLow = (short)(nMaxHrt * _FitHR_RngMin + 0.5);
    //short nRngUpp = (short)(nMaxHrt * _FitHR_RngMax + 0.5);
    
  //cal calories
  CGFloat fCalories = [self calBurnedCalories:nRate second:dDurSeconds wgt:_fBodyWgt age:_nAgeYear sex:_nSexNum];
  if(isnan(fCalories))
     fCalories = 0.0;
  _fBurnedVal = _fBurnedVal + fCalories * 1000.0;
  
  //NSString* sCalUnit = @"C";
  CGFloat fBurnCal = _fBurnedVal;
  if(isnan(fBurnCal) || fBurnCal < 0) {
    fBurnCal = 0;
  }
  /*else if(fBurnCal > 1000) {
    fBurnCal /= 1000.0;
    sCalUnit = @"k-C";
  }*/
  //_lblCalBurnVal.text = [NSString stringWithFormat:@"%.1f %@", fBurnCal, sCalUnit];
  
  if(fBurnCal > 5)
    _lblCalBurnVal.text = [NSString localizedStringWithFormat:@"%.0f", fBurnCal];
  else if(fBurnCal > 1)
    _lblCalBurnVal.text = [NSString localizedStringWithFormat:@"%.1f", fBurnCal];
  else
    _lblCalBurnVal.text = [NSString localizedStringWithFormat:@"%.2f", fBurnCal];

  
    /*if(_nSexNum == 1) {
     fCalories = ((0.2017 * _nAgeYear - 0.09036 * _BodyWgt + 0.6309 * nRate - 55.0969) / 4.184) * (dDurSeconds / 60) / 1000;
     }
     else {
     fCalories = ((0.074 * _nAgeYear - 0.05741 * _BodyWgt + 0.4472 * nRate - 20.4022) / 4.184) * (dDurSeconds / 60) / 1000;
     }
     if(fCalories < 0)
     fCalories = 0;*/
    

    //NSString* sBurned = [NSString stringWithFormat:@"%.3f %@", _fBurnedVal, NSLocalizedString(@"cal", nil)];
    
    
    //_lblBurnedVal.text = sBurned;
    //[_gView updateData:_fBurnedVal];
    
    //local store
    if(nRate > 0 && _hRate != nil)  {
      AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
      if(_dtLastSync != nil) {
        NSDate* dtMeas = _bSyncData?_dtLastSync:_dtMeas;
        if(dtMeas != nil) {
          [pApp updHrateStartEndTime:_hRate startTime:nil endTime:dtMeas toSvr:NO];
          [pApp insertHrateItemData:_nHrateId bodyId:_nBodyId hRate:nRate dtime: dtMeas toSvr:!_bSyncData];
        }
      }
      else if(!_bSyncData && _nHrateId != 0) {
        [pApp updHrateStartEndTime:_hRate startTime:nil endTime:_dtMeas toSvr:YES];
        [pApp insertHrateItemData:_nHrateId bodyId:_nBodyId hRate:nRate dtime:_dtMeas toSvr:YES];
      }
      _nLastHrate = (short)nRate;
    }
}

- (void) showSyncMessage:(NSString*)sMsg
{
  _lblMsg.text = sMsg;
  if(!_actView.isAnimating && !_bBleConnException) {
    [_actView startAnimating];
  }
  /*else if(_bBleConnException) {
     _lblMsg.text = @"BLE Conn. Exception!";
  }*/
}

/*-(void)MyCoreBlueData:(id)data andMark:(NSString *)mark
{
  NSLog(@"data is %@",data);
  if ([mark isEqualToString:@"0"])
  {
    NSMutableString *dataStr = [[NSMutableString alloc] initWithString:data];
    [conRedString appendFormat:@"\n"];
    [conRedString appendString:dataStr];
    contentRed.text = conRedString;
  }
  else
  {
    NSMutableString *dataStr = [[NSMutableString alloc] initWithString:data];
    [conString appendFormat:@"\n"];
    [conString appendString:dataStr];
    content.text = conString;
  }
}

-(void)isConnectState:(NSInteger)code
{
  switch (code)
  {
    case 0:
    {
      [btn setTitle:@"未开启蓝牙" forState:UIControlStateNormal];
      break;
    }
    case 1:
    {
      [btn setTitle:@"已开启蓝牙,点击开始" forState:UIControlStateNormal];
      break;
    }
    case 2:
    {
      [btn setTitle:@"未绑定设备" forState:UIControlStateNormal];
      break;
    }
    case 3:
    {
      [btn setTitle:@"正在搜索蓝牙设备" forState:UIControlStateNormal];
      break;
    }
    case 4:
    {
      [btn setTitle:@"正在连接设备" forState:UIControlStateNormal];
      break;
    }
    case 5:
    {
      [btn setTitle:@"连接设备失败" forState:UIControlStateNormal];
      break;
    }
    case 6:
    {
      [btn setTitle:@"获取服务失败" forState:UIControlStateNormal];
      break;
    }
    case 7:
    {
      [btn setTitle:@"获取服务成功，正在连接数据通道" forState:UIControlStateNormal];
      break;
    }
    case 8:
    {
      [btn setTitle:@"连接数据通道失败" forState:UIControlStateNormal];
      break;
    }
    case 9:
    {
      [btn setTitle:@"连接数据通道成功，正在获取数据" forState:UIControlStateNormal];
      break;
    }
    case 10:
    {
      [btn setTitle:@"获取数据失败" forState:UIControlStateNormal];
      break;
    }
    case 11:
    {
      [btn setTitle:@"获取数据成功，正在获取下一条数据" forState:UIControlStateNormal];
      break;
    }
    case 12:
    {
      [btn setTitle:@"获取数据完毕,重新开始" forState:UIControlStateNormal];
      btn.enabled = YES;
      break;
    }
      
    default:
      break;
  }
}*/
- (BOOL) needUpdHrtEndtime
{
  if(_dtLastSync == nil || _hRate == nil)
    return NO;
  
  BOOL bNeedUpd= YES;
  if(_hRate.hEndDate != nil) {
    if([_dtLastSync timeIntervalSinceDate:_hRate.hEndDate] < 0)
      bNeedUpd = NO;
  }
  return bNeedUpd;
}

- (BOOL) ExistsStartDateHrate:(NSUInteger) nStartUtc
{
  if(_aHrateMemData == nil || _aHrateMemData.count == 0)
    return NO;
    
  NSUInteger nCount = _aHrateMemData.count;
  for(NSUInteger i=0; i<nCount; i++) {
    O_Hrate* pRate = [_aHrateMemData objectAtIndex: i];
    if(pRate != nil) {
      NSUInteger nStart = pRate.nSyncMeasStartUtc;
      if(nStartUtc == nStart)
        return YES;
    }
    else {
      continue;
    }
  }
  return NO;
}

- (void)heartRateHistiryData:(NSNotification *)data
{
  AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  NSDateFormatter* dtFormat = pApp.dtFmt;
  NSString* sInitFmt = dtFormat.dateFormat;
  [dtFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
  
  m_rateArray  = [[NSMutableArray alloc] initWithArray:(NSArray *)data.object];
  NSUInteger nCount = m_rateArray.count;
  
  int nHrateId = 0;
  NSUInteger nLastStartUtc = 0;
  for(NSUInteger i=0; i<nCount; i++) {
    NSString *sportTime = [[m_rateArray objectAtIndex:i] objectForKey:@"sportTime"];
    NSString *heartRate = [[m_rateArray objectAtIndex:i] objectForKey:@"heartRateNum"];
    
    short nHrateVal = (short)heartRate.intValue;
    NSDate* dtMeas = [dtFormat dateFromString:sportTime];
    
    NSUInteger nMeasUtc = (NSUInteger)[dtMeas timeIntervalSince1970];
    
    BOOL bNewMeas = (nMeasUtc - nLastStartUtc) > 129;
    if(bNewMeas) {
      if(![self ExistsStartDateHrate:nMeasUtc]) {
        nHrateId++;
        O_Hrate* pHrate = [[O_Hrate alloc] initHrateData:nMeasUtc end:nMeasUtc hrtId:nHrateId];
        [_aHrateMemData addObject:pHrate];
      }
    }
    
    O_HrateItem* pItem = [[O_HrateItem alloc] initHrateDate:nHrateVal meas:nMeasUtc hrtId:nHrateId];
    [_aHrateItemMemData addObject:pItem];
    
    nLastStartUtc = nMeasUtc;
  }
  //[m_rateTable reloadData];
  NSLog(@"history heart rate is %@", m_rateArray);
  [pApp.dtFmt setDateFormat:sInitFmt];
  
  [self insertHrateDataToDatabase];
  //[self endSyncProc:0 char:nil hRate:0];
}

- (void) recvedBleDevSyncData:(const uint8_t *)rcvData len: (NSUInteger)nDataLen char:(CBCharacteristic *)pChar
{
  _bSyncOldVer = NO;
  _bSyncData = YES;
  
  //huitaike funcs
  //[[HandBlueValue selfAlloc] handBluetoothValue:pChar.value];
  //return;
  
  uint8_t d0 = rcvData[0];
  uint8_t nIdx = d0 & 0x0f; //markNum
  //uint8_t nPackIdx = rcvData[1] & 0x0f; //markLongNum
  
  //short nIdxNo = nIdx; //markNum
  //®short nPackidxNo = nPackIdx; //markLongNum
  
  if(_bSyncDevStop && [_ncitBleDev isTestHRMDevice]) {
    short nHr = rcvData[nDataLen-1];
    [self endSyncProc:d0 char:pChar hRate:nHr];
    //_lblMsg.text = @"Already download memory data!";
    [self performSelectorOnMainThread:@selector(showSyncMessage:) withObject:NSLocalizedString(@"Already download memory data!", nil) waitUntilDone:NO];
    
    if(!_bJustSotreHrateMem)
      _bSyncData = NO;
    return;
  }
  
    //if(!_bSyncData || _bJustStart) {
    /*if(_bJustStart) {
        [self returnDevOk:d0 char:pChar];
        if(_btnSyncTpp.hidden)
            _btnSyncTpp.hidden = NO;
        
        uint8_t val[6] = {0x06, 'd', 'o', 'n', 'e', 0x00};
        val[5] = [self getCheckSum:val len:5];
        NSData* valData = [NSData dataWithBytes:(void*)val length:sizeof(val)];
        [_ncitBleDev sendDataToBleDev:pChar data:valData type: CBCharacteristicWriteWithoutResponse];
        [_ncitBleDev enableSyncChar:pChar enable:NO];
        return;
    }*/
  
    if(nIdx == 0x01) {
      //_lblMsg.text = @"Sending user info...";
      //[self performSelectorOnMainThread:@selector(showSyncMessage:) withObject:@"Sending user info..." waitUntilDone:NO];
      [self sendUserDataToHMDev :d0 char:pChar];
      //[self performSelectorInBackground:@selector(showSyncMessage:) withObject:@"Sending user info..."];
    }
    else if(nIdx == 0x02) {
      //_lblMsg.text = @"sending UTC date...";
      [self performSelectorOnMainThread:@selector(showSyncMessage:) withObject:NSLocalizedString(@"sending UTC date...", nil) waitUntilDone:NO];
      [self sendUtcDateTimeData:d0 char:pChar];
      //[self syncTodayActData:d0 char:pChar];
      //[NSThread sleepForTimeInterval:0.25];
    }
    else if(nIdx == 0x03) {
        [self syncTodayActData:d0 char:pChar];
        _lblMsg.text = NSLocalizedString(@"Today active data rcved", nil);
    }
    else if(nIdx == 0x04) {
        [self syncActDetailData:d0 char:pChar];
        _lblMsg.text = NSLocalizedString(@"Ative details data rcved", nil);
    }
    else if(nIdx == 0x05) {
        [self syncSleepData:d0 char:pChar];
        _lblMsg.text = NSLocalizedString(@"Sleep data synced", nil);
        //[NSThread sleepForTimeInterval:0.25];
    }
    else if(nIdx == 0x07) {
        [self syncDeviceData:d0 char:pChar];
        _lblMsg.text = NSLocalizedString(@"Device inofo group synced", nil);
        //[NSThread sleepForTimeInterval:0.25];
    }
    else if(nIdx == 0x08) {
      if(_bSyncData) {
        //short nPaxkNo = d0 >> 4;
        //_aSyncCheckSum[nPackidxNo] = rcvData[nDataLen-1];
        //[self sendDataBakToHrmForCleƒar:nPaxkNo char:pChar];
        [self syncHrateData:rcvData len:nDataLen char:pChar];
      }
      else {
         _lblMsg.text = NSLocalizedString(@"Commmunication...", nil);
        [self returnDevOk:d0 char:pChar];
      }
    }
    else if(nIdx == 0x09) {
      [self syncCycleData:d0 char:pChar];
      _lblMsg.text = NSLocalizedString(@"Cycle data synced", nil);
      //[NSThread sleepForTimeInterval:0.25];
    }
  
  if(nIdx == 0x06) {
    if(_bJustSotreHrateMem)
      return;
                                     
    _nCountTick = 0;
    _bDownloadMemEnd = YES;
    short nHr = 0;
    
    //uint8_t nPackIdx = rcvData[1];
    [self sendDataBakToHrmForClear:d0>>4 char:pChar];
    
    if(_dtLastSync != nil && _hRate != nil && _nHrateId != 0) {
      //dispatch_sync(dispatch_get_main_queue(), ^{
      AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
      //if([self needUpdHrtEndtime])
        //[pApp updHrateStartEndTime:_hRate startTime: nil endTime:_dtLastSync toSvr:NO];
      nHr = rcvData[nDataLen-1];
      [pApp updHrateStartEndTime:_hRate startTime:nil endTime:_dtLastSync toSvr:NO];
      [pApp insertHrateItemData:_nHrateId bodyId:_nBodyId hRate:nHr dtime: _dtLastSync toSvr: NO];
  
      _hRate = nil;
      //_nHrateId = 0;
      _dtLastSync = nil;
      
      _nLastHrate = nHr;
      _nLastSyncHrate = nHr;
      pApp.m_nHrateId = 0;
      //});
    }
    else if(_hRate == nil && !_bSyncData) {
      _bSyncDevStop = NO;
      _bStoredData = NO;
      if(!_bJustSotreHrateMem)
        _bSyncData = NO;
      _dtMeas = [NSDate date];
      _bSureNew = YES;
      [self insertStartHRMData:_dtMeas];
    }
    
    _bSyncData = YES;
    [self endSyncProc:d0 char:pChar hRate:nHr];
    //[self endOneSyncData:0];
    if(_bContBleDev)
      _lblStartStop.text = @"STOP";
    
    /*if(!_bSyncData && !_bJustStart) {
      [_ncitBleDev enableSyncChar:_ncitBleDev.pBleDevChar enable:NO];
    }
    if(_bSyncData && _bJustStart) { //update sync end datetime
      if(_dtLastSync != nil) {
        [self endOneSyncData];
        _dtLastSync = nil;
      }
    }
    
    if(_ncitBleDev.bSyncDevData && !_bJustStart && _bSyncData) {
      [_ncitBleDev stopMeas];
      if(!_bSyncData) {
        _lblMsg.text = @"HM init completed, Tap play to go";
      }
      else {
        _lblMsg.text = _bSyncData? @"Sync completed!": @"Setting completed!";
      }
    }
    else {
      _bSyncData = NO;
      [self insertStartHRMData:[NSDate date]]; //new meas
    }*/
  }
}

- (void) insertHrateDataToDatabase
{
  if(_aHrateMemData == nil || _aHrateMemData.count == 0 || _aHrateItemMemData == nil || _aHrateItemMemData.count == 0)
    return;
 
  _bJustSotreHrateMem = YES;
  NSInteger nCount = _aHrateMemData.count;
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  
  //O_Hrate* objLast = [_aHrateMemData objectAtIndex:nCount-1];
  
  for(NSInteger i=0; i<nCount; i++) {
    O_Hrate* objHrate = [_aHrateMemData objectAtIndex:i];
    NSUInteger utcFirst = objHrate.nSyncMeasStartUtc;
    NSUInteger utcEnd = objHrate.nSyncMeasEndUtc;
    NSDate* dtFirst = [NSDate dateWithTimeIntervalSince1970:(NSTimeInterval)utcFirst];
    NSDate* dtEnd = [NSDate dateWithTimeIntervalSince1970:(NSTimeInterval)utcEnd];
    
    _bSyncData = YES;
    _bSureNew = [_ncitBleDev isTestHRMDevice]? NO: YES;
    _bStoredData = NO;
    _hRate = nil;
    _nHrateId= 0;
    
    //[self insertStartHRMData:dtFirst];
    [self performSelectorOnMainThread:@selector(insertStartHRMData:) withObject:dtFirst waitUntilDone:YES];
    if(_nHrateId != 0 && _hRate != nil) {
      [pApp updHrateStartEndTime:_hRate startTime:nil endTime:dtEnd toSvr:NO];
    }
    else if(_nHrateId == 0) {
      [pApp showAlertBox:NSLocalizedString(@"save data to DB", nil) msg:NSLocalizedString(@" insert data to databse error happened!", nil)];
      continue;
    }
    
    
    int nHrateId = objHrate.nHrateId;
    NSUInteger nItemCount = _aHrateItemMemData.count;
    for(NSUInteger j=0; j<nItemCount; j++) {
      O_HrateItem* item = [_aHrateItemMemData objectAtIndex:j];
      if(item == nil || item.nHrateId != nHrateId)
        continue;
      
      short nBpm = item.nHrateVal;
      NSUInteger nMeasUtc = item.nSyncMeasUtc;
      NSDate* dtItem = [NSDate dateWithTimeIntervalSince1970:(NSTimeInterval)nMeasUtc];

      //dispatch_async(dispatch_get_main_queue(), ^{
        [pApp insertHrateItemData:_nHrateId bodyId:_nBodyId hRate:nBpm dtime: dtItem toSvr: NO];
      //});

      NSString* sMsg = [NSString stringWithFormat:NSLocalizedString(@"Store Memory Data (%ld/%ld)", nil), (unsigned long)(j+1), (unsigned long)nItemCount];
        
//        NSString* sMsg = NSLocalizedString(@"Store Memory Data", nil);
        [self performSelectorInBackground:@selector(showSyncMessage:) withObject:sMsg];
    }
  }
  
  [_aHrateMemData removeAllObjects];
  [_aHrateItemMemData removeAllObjects];
  
  _bSyncData = NO;
  //bSureNew = NO;
  _hRate = nil;
  _bStoredData = NO;
  _bJustSotreHrateMem = NO;
  
  //[self performSelectorOnMainThread:@selector(stopActindicator::) withObject:@"Sotre End" waitUntilDone:YES];
}

- (void) endSyncProc:(uint8_t)d0 char:(CBCharacteristic *)pChar hRate:(short)nBmp
{
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  
  _bJustStart = NO;
  _bSyncException = NO;
  _pSyncChar = pChar;
  
  if(pChar != nil)
    [self returnDevOk:d0 char:pChar];
  
  if(_dtLastSync != nil) {
    [self endOneSyncData:nBmp];
    _dtLastSync = nil;
  }
  //[_ncitBleDev enableSyncChar:_ncitBleDev.pBleDevChar enable:YES];
  //[_ncitBleDev stopMeas];
  
  if(pChar != nil) {
    [self performSelectorOnMainThread:@selector(showSyncMessage:) withObject: NSLocalizedString(@"Start HRM...", nil) waitUntilDone:YES];
    [NSThread sleepForTimeInterval:0.050];
    _measTimer = [NSTimer scheduledTimerWithTimeInterval:12.00 target:self selector:@selector(onMeasTimer) userInfo:nil repeats:NO];
    [_ncitBleDev enableSyncChar:pChar enable:NO];
  }
  else {
    [self performSelectorOnMainThread:@selector(showSyncMessage:) withObject: NSLocalizedString(@"Search HRM service...", nil) waitUntilDone:YES];
    [NSThread sleepForTimeInterval:0.050];
    [_ncitBleDev startMeas:@"180D"];
  }
  
  BOOL bJustSyncEnd = _bSyncData;
  if(bJustSyncEnd && _nDownloadMemHrateId < 0 && _bDownloadMemEnd) {
    NSString* sHrateId = [NSString stringWithFormat:@"%ld", (long)_nDownloadMemHrateId];
    [pApp updHrateSyncLastIdx:sHrateId lastIdx:-3];
    
    NSUserDefaults *userSetting = [NSUserDefaults standardUserDefaults];
    [userSetting setInteger:-3 forKey:kSync_LastMemDldIdx];
    [userSetting synchronize];
    
    _nDownloadIdx = 0;
    _nHrateId = 0;
    
    //_hRate = nil; rem it or not online hrate
    //if(_bSyncDevStop)
    //_lblMsg.text = @"Already Download Data!";
    //_bSyncDevStop = YES;
  }
  
  //if(_bSyncDevStop) {
    //_bSyncData = NO;
    _bStoredData = NO;
    _hRate = nil;

  //}
  
  //[self performSelectorOnMainThread:@selector(saveDataToDatabase:) withObject:@"Store Membory Hrate Data..." waitUntilDone:NO];
  //[_lblMsg performSelectorOnMainThread:@selector(setText:) withObject:@"Store Membory Hrate Data..." waitUntilDone:YES];
  //[self performSelectorOnMainThread:@selector(showSyncMessage:) withObject:@"Store Memory Hrate Data..." waitUntilDone:YES];
  [self performSelectorInBackground:@selector(showSyncMessage:) withObject:NSLocalizedString(@"Store Memory Hrate Data...", nil)];
  [self insertHrateDataToDatabase];
  
  //if(pChar != nil)
  [self performSelectorOnMainThread:@selector(stopActindicator:) withObject:NSLocalizedString(@"Init & Sync OK, Measurement...", nil) waitUntilDone:NO];
  /*UIImage* iBtn = [UIImage imageNamed:@"btn-stop.png"];
  [_btnStartStop setBackgroundImage:iBtn forState:UIControlStateNormal];
  _lblStartStop.text = @"STOP";
  _btnStartStop.hidden = NO;*/
  
  _hRate = nil;
  _bStoredData = NO;
  
  if(!_bJustSotreHrateMem)
    _bSyncData = NO;
  _dtMeasStart = [NSDate date];
  _dtMeas = [NSDate date];
  _bSureNew = YES;
  [self insertStartHRMData:_dtMeas];
  _bSyncDevStop = NO;
}

- (uint8_t) getCheckSum:(uint8_t *)pVal len:(short)nLen
{
    uint8_t nSum = 0;
    for(short i=0; i<nLen; i++) {
        nSum += pVal[i];
    }
    return nSum;
}

- (void) sendUserDataToHMDev:(uint8_t) d0 char:(CBCharacteristic*)aChar
{
    AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
    //_lblMsg.text = @"Init data";
    uint8_t nIdx = d0 >> 4;
    short nWgt = _fBodyWgt * 10;
    uint8_t nWgth = nWgt >> 8;
    uint8_t nWgtl = nWgt & 0xff;
    uint8_t nStepLen = _nHgtMm * 0.0404;
    
    int nGoalSteps = pApp.m_bodyInfo.nGoalStep;
    uint8_t nStep_h = (nGoalSteps & 0x0f00) >> 16;
    uint8_t nStep_m =  (nGoalSteps & 0x00f0) >> 8;
    uint8_t nStep_l =  nGoalSteps & 0x000f;
    

  uint8_t val[12] = {0xe1, nIdx, nWgth, nWgtl, _nAgeYear, _nHgtMm / 10, nStepLen, _nSexNum, nStep_h, nStep_m, nStep_l, 0x00};
  val[11] = [self getCheckSum:val len:11];
  BOOL bSavedUuid = pApp.m_bStoredBleUuid;
  if(bSavedUuid) {
    val[0] = 0xe0;
    val[1] = nIdx;
    val[2] = 0x00;
    val[3] = [self getCheckSum:val len:3];
  }
  else {
    pApp.m_bStoredBleUuid = YES;
  }
    
  NSData* valData = [NSData dataWithBytes:(void*)val length:bSavedUuid?4:sizeof(val)];
    [_ncitBleDev sendDataToBleDev:aChar data:valData type: CBCharacteristicWriteWithoutResponse];
    //[_ncitBleDev sendDataToBleDev:aChar data:valData type: CBCharacteristicWriteWithoutResponse];
    //[_ncitBleDev sendDataToBleDev:aChar data:valData type: CBCharacteristicWriteWithResponse];
    NSLog(@"Send User Sync Data with: %@", aChar.UUID);
}

- (void) sendUtcDateTimeData:(uint8_t) d0 char:(CBCharacteristic*)aChar
{
    uint8_t nIdx = d0 >> 4;
    NSDate* dt = [NSDate date];
    
    //not need time difference
    /*NSTimeZone* locZone = [NSTimeZone systemTimeZone];
    NSInteger nInterval = [locZone secondsFromGMTForDate:dt];
    dt = [dt dateByAddingTimeInterval: nInterval];*/
    NSUInteger dtScds = [dt timeIntervalSince1970];
    //dtScds += 8 * 60 * 60;
    
    uint8_t nUtch1 = (dtScds & 0xff000000) >> 24;
    uint8_t nUtch2 = (dtScds & 0x00ff0000) >> 16;
    uint8_t nUtch3 = (dtScds & 0x0000ff00) >> 8;
    uint8_t nUtch4 = (dtScds & 0x000000ff);
    
    uint8_t val[7] = {0xe2, nIdx, nUtch1, nUtch2, nUtch3, nUtch4, 0x00};
    val[6] = [self getCheckSum:val len:6];
    
    NSData* valData = [NSData dataWithBytes:(void*)val length:sizeof(val)];
    [_ncitBleDev sendDataToBleDev:aChar data:valData type: CBCharacteristicWriteWithoutResponse];
    
    NSLog(@"Send UTC Sync Data: %X", val[0]);
}

- (void) syncTodayActData:(uint8_t) d0 char:(CBCharacteristic*)aChar
{
    uint8_t nIdx = d0 >> 4;
    
    uint8_t val[4] = {0xe0, nIdx, 0x00, 0x00};
    val[3] = [self getCheckSum:val len:3];
    
    NSData* valData = [NSData dataWithBytes:(void*)val length:sizeof(val)];
    [_ncitBleDev sendDataToBleDev:aChar data:valData type: CBCharacteristicWriteWithoutResponse];
    
    NSLog(@"Send Today Act Data: %X", val[0]);
}

- (void) syncActDetailData:(uint8_t) d0 char:(CBCharacteristic*)aChar
{
    uint8_t nIdx = d0 >> 4;
    
    uint8_t val[4] = {0xe0, nIdx, 0x00, 0x00};
    val[3] = [self getCheckSum:val len:3];
    
    NSData* valData = [NSData dataWithBytes:(void*)val length:sizeof(val)];
    [_ncitBleDev sendDataToBleDev:aChar data:valData type: CBCharacteristicWriteWithoutResponse];
    
    NSLog(@"Send Act Details Sync Data: %X", val[0]);
    
}

- (void) syncSleepData:(uint8_t) d0 char:(CBCharacteristic*)aChar
{
    uint8_t nIdx = d0 >> 4;
    
    uint8_t val[4] = {0xe0, nIdx, 0x00, 0x00};
    val[3] = [self getCheckSum:val len:3];
    
    NSData* valData = [NSData dataWithBytes:(void*)val length:sizeof(val)];
    [_ncitBleDev sendDataToBleDev:aChar data:valData type: CBCharacteristicWriteWithoutResponse];
    
    NSLog(@"Send Seep Sync Data: %X", val[0]);
}

- (void) syncDeviceData:(uint8_t) d0 char:(CBCharacteristic*)aChar
{
    uint8_t nIdx = d0 >> 4;
    
    uint8_t val[4] = {0xe0, nIdx, 0x00, 0x00};
    val[3] = [self getCheckSum:val len:3];
    
    NSData* valData = [NSData dataWithBytes:(void*)val length:sizeof(val)];
    [_ncitBleDev sendDataToBleDev:aChar data:valData type: CBCharacteristicWriteWithoutResponse];
    
    //[NSThread sleepForTimeInterval:0.25];
    //[_ncitBleDev disablePedoSyncSvr];
    
    NSLog(@"Send Device Sync Data: %X", val[0]);
}

- (void) sendDataBakToHrmForClear:(uint8_t)nIdx char:(CBCharacteristic *)pChar
{
  //return;
  
  if(pChar == nil)
    return;
  
  uint8_t val[4] = {0xe0, nIdx, 0x00, 0x00};
  val[3] = [self getCheckSum:val len:3];
  NSData* valData = [NSData dataWithBytes:(void*)val length:sizeof(val)];
  [_ncitBleDev sendDataToBleDev:pChar data:valData type: CBCharacteristicWriteWithoutResponse];
}

- (void) updateHrateItemEndTimeCache:(O_Hrate*) hRate
{
//NSDate* dtMeas = _dtLastSync;
  NSUInteger nCount = _aHrateMemData.count;
  if(nCount == 0)
    return;
  
  for(NSUInteger i=0; i<nCount; i++) {
    O_Hrate* pRate = [_aHrateMemData objectAtIndex:i];
    if((pRate.nHrateId == hRate.nHrateId)/*|| (pRate.nSyncMeasStartUtc == hRate.nSyncMeasStartUtc) || (hRate.nSyncMeasStartUtc > 0 && hRate.nSyncMeasStartUtc == hRate.nSyncMeasEndUtc)*/) {
      //int nHrateId = pRate.nHrateId;
      //NSUInteger nDelta = hRate.nSyncMeasEndUtc;
      pRate.nSyncMeasEndUtc = hRate.nSyncMeasEndUtc;
      return;
    }
  }

}


- (void) updateHrateItemEndTimeDb:(AppDelegate *) pApp
{
  NSDate* dtMeas = _dtLastSync;
  if(_hRate == nil || _dtLastSync == nil || _nHrateId == 0 || _nLastHrate <= 0)
    return;
  
  [pApp updHrateStartEndTime:_hRate startTime:nil endTime:dtMeas toSvr:NO];
  [pApp insertHrateItemData:_nHrateId bodyId:_nBodyId hRate:_nLastHrate dtime: dtMeas toSvr: NO];

   
  _nHrateId = 0;
  _hRate = nil;
  _dtLastSync = nil;
}

/*- (void) syncHrateData:(const uint8_t *)rcvData len: (NSUInteger)nDataLen char:(CBCharacteristic *)pChar
{
  if(_nInitIdx == -3 || _bSyncDevStop) {
    [self endOneSyncData:0];
    return;
  }
  //if(_nDownloadIdx < _nInitIdx)_nDownloadIdx < _nInitIdx
  //return;
  
  if(nDataLen > 20) {
    nDataLen = 20;
  }
  //int nAddIdx = 0;
  
  uint8_t d0 = rcvData[0];
  uint8_t nIdx = d0 >> 4;
  if(_bSyncData) {
    uint8_t nPackIdx = rcvData[1];
    if(nPackIdx >= __nSyncPackCount)
      return;
    
    //if(nPackIdx == 0x05) {
      //[self sendDataBakToHrmForClear: nIdx char:pChar];
    //}
    
    if(_aSyncCheckSum[nPackIdx] == rcvData[nDataLen-1]) {
      return;
    }
    
    if(_nSyncLastUtc > 0 && nPackIdx > 1 && nPackIdx < 5)
      _bSyncDataError = (nPackIdx-_nLastSyncIdx != 1);
    else
      _bSyncDataError = NO;
    if(_bSyncDataError)
      return;
    
    AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    BOOL bNewSyncMeas = nPackIdx == 0x01;
    int nStart = bNewSyncMeas?6:2;
    _bNewSyncMeas = bNewSyncMeas;
    
    BOOL bNeedInsNew = bNewSyncMeas;
    NSDate* dtMeas = nil;
    NSUInteger nSyncCurtUtc = 0;
    if(bNewSyncMeas) {
      nSyncCurtUtc = (rcvData[2] << 24) + (rcvData[3] << 16) + (rcvData[4] << 8) + rcvData[5];
    
      if(nSyncCurtUtc == _nSyncStartUtc && _nSyncStartUtc > 0) {
        //_nSyncLastUtc = 0;
        [self sendDataBakToHrmForClear: nIdx char:pChar];
        return;
      }
      //nAddIdx = 0;
      
      dtMeas = [NSDate dateWithTimeIntervalSince1970:(NSTimeInterval)nSyncCurtUtc];
      
      
      if(nSyncCurtUtc > 0 && _nSyncStartUtc > 0 && _nSyncLastUtc > 0) {
        bNeedInsNew = (int)(nSyncCurtUtc - _nSyncStartUtc) > 179 && (int)(nSyncCurtUtc - _nSyncLastUtc) > 119;
        //bNeedInsNew = (nSyncCurtUtc > _nSyncLastUtc) && [dtMeas timeIntervalSinceDate:_dtLastSync] > 9;
      }
      
      _nSyncStartUtc = nSyncCurtUtc;
      _nSyncLastUtc = nSyncCurtUtc;
    }
    
    if(dtMeas != nil) { //&& ![dtMeas isEqual: _dtSyncStart]
      if(bNeedInsNew) {
        _nSyncStartUtc = nSyncCurtUtc;
        _nSyncLastUtc = nSyncCurtUtc;
        _dtSyncStart = [NSDate dateWithTimeIntervalSince1970:(NSTimeInterval)nSyncCurtUtc];
        
        if(_hRate != nil && _dtLastSync != nil && _nHrateId != 0 && _nLastHrate > 0) {
          [self updateHrateItemEndTime: pApp meas:_dtLastSync];
        }
        else { //chek if sync complete
          H_Rate* pHrate = [pApp loadHrateStartRcd:_nBodyId start:_dtSyncStart];
          if(pHrate != nil) {
            NSInteger nLastIdx = pHrate.nLastUpdIdx.integerValue;
            if(nLastIdx == -1 || nLastIdx == -3) {
              _bSyncDevStop = YES;
              return;
            }
          }
        }
        
        _hRate = nil;
        _bSyncData = YES;
        _bStoredData = NO;//((nSyncCurtUtc > _nSyncLastUtc) && (int)(nSyncCurtUtc - _nSyncLastUtc) > 149)?NO: YES;
        
        _dtLastSync = [NSDate dateWithTimeIntervalSince1970:(NSTimeInterval)nSyncCurtUtc];//dtMeas;
        _nSyncStartUtc = nSyncCurtUtc;
        
        if([self insertStartHRMData:dtMeas]) {
          _nDownloadIdx = 0;
          short nHrate = rcvData[nStart];
          [pApp insertHrateItemData:_nHrateId bodyId:_nBodyId hRate:nHrate dtime: dtMeas toSvr: NO];
          
          //reset init pos
          NSUserDefaults *userSetting = [NSUserDefaults standardUserDefaults];
          [userSetting setInteger:0 forKey: kSync_LastMemDldIdx];
          [userSetting synchronize];
          _nLastIdx = 0;
          _nInitIdx = 0;
        }
        
        _dAvgHrate = 0.0;
        _nAvgHrate = 0;
        _nMaxHrate = 0;
        _nMinHrate = 1000;
        _fBurnedVal = 0.0;
        _nCountTick = 0;
        [self resetCtrlsDate];
        
        _dtMeasStart = [dtMeas dateByAddingTimeInterval:0];
        _dtMeas = [_dtMeasStart dateByAddingTimeInterval:0];
        
        //debug
        //[_ncitBleDev sendDebugHrate:0 dtStart:dtMeas dtEnd: _dtLastSync count:0];
        //debug
        
        _bSyncSentEndDataToSvr = NO;
        //_dtLastSync = [dtMeas dateByAddingTimeInterval:0];//[dtMeas initWithTimeIntervalSinceReferenceDate:0];
        _dtLastSync = [NSDate dateWithTimeIntervalSince1970:(NSTimeInterval)nSyncCurtUtc];
      }
    }
    
    
    //_nInitIdx = 0;
    //uint8_t nHr = 0;
    BOOL bGetData = NO;
    if(nDataLen != 4 && nPackIdx != 5) {
      if(_bSyncDataError && [dtMeas timeIntervalSinceDate:_dtLastSync] <= 0)
        return;
      
      
      //NSDate* dtEnd = nil;
      //H_Rate* pHrate = nil;
      for(int i=nStart; i<nDataLen-1; i++) {
        short nHr = rcvData[i];
        _nLastHrate = nHr;
        if(nHr > 0 && _dtLastSync != nil && _nHrateId != 0)  {
          _bSyncSentEndDataToSvr = NO;
          //[self addHrateSyncVal:nHr];
          
          //nSyncCurtUtc += 2;
          _nSyncLastUtc += 2;
          _nSyncItemCount++;
          _nSyncTotalCount++;
          _dtLastSync = [NSDate dateWithTimeIntervalSince1970:(NSTimeInterval)_nSyncLastUtc];
          
          short nBpm = 0;
          if(_hRate != nil && _nDownloadIdx >= _nInitIdx &&& _nHrateId != 0) {
            nBpm = nHr;
          }
          
          // && [_dtLastSync timeIntervalSinceDate:_dtSyncStart] < 179
          if(_dtLastSync != nil && _hRate != nil && _nHrateId != 0) {
            [pApp insertHrateItemData:_nHrateId bodyId:_nBodyId hRate:nBpm dtime: _dtLastSync toSvr: NO];
            [pApp updHrateStartEndTime:_hRate startTime: nil endTime:_dtLastSync toSvr:NO];
            bGetData = YES;
          }
          else if(_hRate == nil ||  _nHrateId == 0) {
            [pApp showAlertBox:@"_hRate == nil & _nHrateId == 0" msg:@"Hrat data store issues!"];
            bGetData = NO;
          }
        }
      }
      //if(dtEnd != nil && pHrate != nil)
      //[pApp updHrateStartEndTime:pHrate startTime:dtEnd endTime:nil toSvr:NO];
      
      _aSyncCheckSum[nPackIdx] = rcvData[nDataLen-1];
      
      _nDownloadIdx++;
      _nSyncPackIdx++;
    }
    //debug end date time
    //if(nDataLen == 4)
    //[_ncitBleDev sendDebugHrate: -1 dtStart:nil dtEnd:_dtLastSync count:-1];
    //debug
    
    _nLastSyncIdx = nPackIdx;
    if(nPackIdx == 0x05) {
      [self sendDataBakToHrmForClear: nIdx char:pChar];
    }
    
    //!_bSyncDevStop && _nDownloadIdx >= _nInitIdx && _dtLastSync != nil && _nHrateId != 0*
    if(bGetData && !_bSyncDevStop && _nDownloadIdx >= _nInitIdx && _dtLastSync != nil && _hRate != nil && _nHrateId != 0) {
      NSString* sMsg = [NSString stringWithFormat:@"Downloading Memory (%i)", _nDownloadIdx];
      [self performSelectorInBackground:@selector(showSyncMessage:) withObject:sMsg];
    }
    else if(_nDownloadIdx < _nInitIdx) {
      NSString* sMsg = _lblMsg.text;
      if([sMsg rangeOfString:@"Downloading"].location == NSNotFound) {
        sMsg = @"Check Break Point Data...";
        [self performSelectorInBackground:@selector(showSyncMessage:) withObject:sMsg];
      }
    }
  }
}*/

- (void) syncHrateData:(const uint8_t *)rcvData len: (NSUInteger)nDataLen char:(CBCharacteristic *)pChar
{
  if(_nInitIdx == -3 || _bSyncDevStop) {
    [self endOneSyncData:0];
    return;
  }
  //if(_nDownloadIdx < _nInitIdx)_nDownloadIdx < _nInitIdx
  //return;
  
  if(nDataLen > 20) {
    nDataLen = 20;
  }
  //int nAddIdx = 0;
  
  uint8_t d0 = rcvData[0];
  uint8_t nIdx = d0 >> 4;
  int nHrateId = _nLastSyncMemHrateId;
  if(_bSyncData) {
    uint8_t nPackIdx = rcvData[1];
    if(nPackIdx >= __nSyncPackCount)
      return;
    
    if(nPackIdx == 0x01) {
      _nLastSyncPos = d0;
    }
    
    if(/*nPackIdx == 5 && */_aSyncCheckSum[nPackIdx] == rcvData[nDataLen-1]) {
      //_nLastSyncPos = 0;
      //[self sendDataBakToHrmForClear:nIdx char:pChar];
      return;
    }
    
    if(_nSyncLastUtc > 0 && nPackIdx > 1 && nPackIdx < 5)
      _bSyncDataError = (nPackIdx-_nLastSyncIdx != 1);
    else
      _bSyncDataError = NO;
    if(_bSyncDataError)
      return;
    
    AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    BOOL bNewSyncMeas = nPackIdx == 0x01;
    int nStart = bNewSyncMeas?6:2;
    _bNewSyncMeas = bNewSyncMeas;
    
    BOOL bNeedInsNew = bNewSyncMeas;
    NSDate* dtMeas = nil;
    NSUInteger nSyncCurtUtc = 0;
    if(bNewSyncMeas) {
      //if(_nLastSyncPos == d0)
        //return;
      
      nSyncCurtUtc = (rcvData[2] << 24) + (rcvData[3] << 16) + (rcvData[4] << 8) + rcvData[5];
      
      if((/*_nLastSyncPos == d0 || */nSyncCurtUtc == _nSyncStartUtc) && _nSyncStartUtc > 0) {
        //_nSyncLastUtc = 0;
        [self sendDataBakToHrmForClear: nIdx char:pChar];
        return;
      }
      //nAddIdx = 0;
      
      dtMeas = [NSDate dateWithTimeIntervalSince1970:(NSTimeInterval)nSyncCurtUtc];
      
      if(nSyncCurtUtc > 0 && _nSyncStartUtc > 0 && _nSyncLastUtc > 0 && _nLastSyncPos > 0) {
        bNeedInsNew = (int)(nSyncCurtUtc - _nSyncStartUtc) > 179 && (int)(nSyncCurtUtc - _nSyncLastUtc) > 129;
        //bNeedInsNew = (nSyncCurtUtc > _nSyncLastUtc) && [dtMeas timeIntervalSinceDate:_dtLastSync] > 9;
      }
      
      //_nSyncStartUtc = nSyncCurtUtc;
      //_nSyncLastUtc = nSyncCurtUtc;
    }
    
    if(dtMeas != nil) { //&& ![dtMeas isEqual: _dtSyncStart]
      if(bNeedInsNew && _nLastSyncPos > 0) {
        nHrateId++;
        
        //_bSureNew = YES;
        if(_nLastHrate > 0 && _nSyncStartUtc > 0 && _nSyncStartUtc != _nSyncLastUtc) {
          O_Hrate* hRate = [[O_Hrate alloc] initHrateData:_nSyncStartUtc end:_nSyncLastUtc hrtId:(int)_nLastSyncMemHrateId];
          [self updateHrateItemEndTimeCache: hRate];
          //[_aHrateMemData addObject:hRate];
          //[self updateHrateItemEndTime: pApp meas:_dtLastSync];
          //[self performSelectorOnMainThread:@selector(updateHrateItemEndTime:) withObject:pApp waitUntilDone:YES];
          //_bSureNew = NO;
        }
        else { //chek if sync complete
          H_Rate* pHrate = [pApp loadHrateStartRcd:_nBodyId start:_dtSyncStart];
          if(pHrate != nil) {
            NSInteger nLastIdx = pHrate.nLastUpdIdx.integerValue;
            if((nLastIdx == -1 || nLastIdx == -3) && [_ncitBleDev isTestHRMDevice]) {
              _bSyncDevStop = YES;
              return;
            }
          }
        }
        _nLastSyncMemHrateId = nHrateId;
        _nSyncStartUtc = nSyncCurtUtc;
        _dtSyncStart = [NSDate dateWithTimeIntervalSince1970:(NSTimeInterval)_nSyncStartUtc];
        _nSyncLastUtc = nSyncCurtUtc;
        
        _hRate = nil;
        _bSyncData = YES;
        _bStoredData = NO;//((nSyncCurtUtc > _nSyncLastUtc) && (int)(nSyncCurtUtc - _nSyncLastUtc) > 149)?NO: YES;
        
        _dtLastSync = [NSDate dateWithTimeIntervalSince1970:(NSTimeInterval)nSyncCurtUtc];//dtMeas;
        //_nSyncStartUtc = nSyncCurtUtc;
        
        if(_nInitIdx <= 0) {
          NSUserDefaults *userSetting = [NSUserDefaults standardUserDefaults];
          _nInitIdx = (int)[userSetting integerForKey:kSync_LastMemDldIdx];
        }
        //if(_nInitIdx > 0)
          //_bSureNew = NO;
        
        if(![self ExistsStartDateHrate:_nSyncStartUtc]) {
          _nDownloadIdx = 0;
          O_Hrate* hRate = [[O_Hrate alloc] initHrateData:_nSyncStartUtc end:_nSyncLastUtc hrtId:nHrateId];
          [_aHrateMemData addObject:hRate];
        }
        //_bNewFinished = NO;
        /*[self performSelectorOnMainThread:@selector(insertStartHRMData:) withObject:dtMeas waitUntilDone:YES];
        if(_bNewFinished) {
          _nDownloadIdx = 0;
          short nHrate = rcvData[nStart];
          //[pApp insertHrateItemData:_nHrateId bodyId:_nBodyId hRate:nHrate dtime: dtMeas toSvr: NO];
          
          //reset init pos
          NSUserDefaults *userSetting = [NSUserDefaults standardUserDefaults];
          [userSetting setInteger:0 forKey: kSync_LastMemDldIdx];
          [userSetting synchronize];
          _nLastIdx = 0;
          _nInitIdx = 0;
        }*/
        
        _dAvgHrate = 0.0;
        _nAvgHrate = 0;
        _nMaxHrate = 0;
        _nMinHrate = 1000;
        _fBurnedVal = 0.0;
        _nCountTick = 0;
        [self resetCtrlsDate];
        
        _dtMeasStart = [dtMeas dateByAddingTimeInterval:0];
        _dtMeas = [_dtMeasStart dateByAddingTimeInterval:0];
        
        //debug
        //[_ncitBleDev sendDebugHrate:0 dtStart:dtMeas dtEnd: _dtLastSync count:0];
        //debug
        
        _bSyncSentEndDataToSvr = NO;
        //_dtLastSync = [dtMeas dateByAddingTimeInterval:0];//[dtMeas initWithTimeIntervalSinceReferenceDate:0];
        _dtLastSync = [NSDate dateWithTimeIntervalSince1970:(NSTimeInterval)nSyncCurtUtc];
      }
    }
    
    
    //_nInitIdx = 0;
    //uint8_t nHr = 0;
    BOOL bGetData = NO;
    if(nDataLen > 4 && nPackIdx < 5 && _nLastSyncPos > 0) {
      if(_bSyncDataError && [dtMeas timeIntervalSinceDate:_dtLastSync] <= 0)
        return;
      
      //NSDate* dtEnd = nil;
      //H_Rate* pHrate = nil;
      for(int i=nStart; i<nDataLen-1; i++) {
        short nHr = rcvData[i];
        _nLastHrate = nHr;
        if(nHr > 0 && _dtLastSync != nil /*&& _nHrateId != 0*/)  {
          _bSyncSentEndDataToSvr = NO;
          //[self addHrateSyncVal:nHr];
          
          //nSyncCurtUtc += 2;
          _nSyncLastUtc += 2;
          _nSyncItemCount++;
          _nSyncTotalCount++;
          _dtLastSync = [NSDate dateWithTimeIntervalSince1970:(NSTimeInterval)_nSyncLastUtc];
          
          short nBpm = nHr;
          //if(_hRate != nil && _nDownloadIdx >= _nInitIdx &&& _nHrateId != 0) {
            //nBpm = nHr;
          //}
          
          // && [_dtLastSync timeIntervalSinceDate:_dtSyncStart] < 179
          if(_nSyncLastUtc > 0 /*&& _hRate != nil && _nHrateId != 0*/) {
            //[pApp insertHrateItemData:_nHrateId bodyId:_nBodyId hRate:nBpm dtime: _dtLastSync toSvr: NO];
            //[pApp updHrateStartEndTime:_hRate startTime: nil endTime:_dtLastSync toSvr:NO];
            
            //NSDate* dtMeasHrate = [_dtLastSync dateByAddingTimeInterval:0];
            O_HrateItem* item = [[O_HrateItem alloc] initHrateDate: nBpm meas:_nSyncLastUtc hrtId:nHrateId];
            [_aHrateItemMemData addObject:item];
            bGetData = YES;
          }
          /*else if(_hRate == nil ||  _nHrateId == 0) {
            [pApp showAlertBox:@"_hRate == nil & _nHrateId == 0" msg:@"Hrat data store issues!"];
            bGetData = NO;
          }*/
        }
      }
      //if(dtEnd != nil && pHrate != nil)
      //[pApp updHrateStartEndTime:pHrate startTime:dtEnd endTime:nil toSvr:NO];
      
      _aSyncCheckSum[nPackIdx] = rcvData[nDataLen-1];
      
      _nDownloadIdx++;
      _nSyncPackIdx++;
    }
    //debug end date time
    //if(nDataLen == 4)
    //[_ncitBleDev sendDebugHrate: -1 dtStart:nil dtEnd:_dtLastSync count:-1];
    //debug
    
    _nLastSyncIdx = nPackIdx;
    if(nPackIdx == 0x05/* && _aSyncCheckSum[nPackIdx] == rcvData[nDataLen-1]*/) {
      _nLastSyncPos = 0;
      if(_nLastHrate > 0 && _nSyncStartUtc > 0 && _nSyncStartUtc != _nSyncLastUtc) {
        O_Hrate* hRate = [[O_Hrate alloc] initHrateData:_nSyncStartUtc end:_nSyncLastUtc hrtId:(int)_nLastSyncMemHrateId];
        [self updateHrateItemEndTimeCache: hRate];
      }
    }
    else if(nPackIdx == 0x01) {
      _nLastSyncPos = d0;
    }
    //if(nPackIdx != 6)
    [self sendDataBakToHrmForClear: nIdx char:pChar];
    
    //!_bSyncDevStop && _nDownloadIdx >= _nInitIdx && _dtLastSync != nil && _nHrateId != 0*
    if(bGetData && !_bSyncDevStop && _nDownloadIdx >= _nInitIdx && _dtLastSync != nil /*&& _hRate != nil && _nHrateId != 0*/) {
      NSString* sMsg = [NSString stringWithFormat:NSLocalizedString(@"Downloading Memory (%i)", nil), _nDownloadIdx];
      //[self performSelectorInBackground:@selector(showSyncMessage:) withObject:sMsg];
      [self performSelectorOnMainThread:@selector(showSyncMessage:) withObject:sMsg waitUntilDone:YES];
    }
    else if(_nDownloadIdx < _nInitIdx) {
      NSString* sMsg = _lblMsg.text;
      if([sMsg rangeOfString:NSLocalizedString(@"Downloading", nil)].location == NSNotFound) {
        sMsg = NSLocalizedString(@"Check Break Point Data...", nil);
        [self performSelectorInBackground:@selector(showSyncMessage:) withObject:sMsg];
      }
    }
  }

  /*if(_nInitIdx == -3 || _bSyncDevStop) {
    [self endOneSyncData:0];
    return;
  }
  //if(_nDownloadIdx < _nInitIdx)_nDownloadIdx < _nInitIdx
    //return;
  
  if(nDataLen > 20) {
    nDataLen = 20;
  }
  //int nAddIdx = 0;
  
    uint8_t d0 = rcvData[0];
    uint8_t nIdx = d0 >> 4;
    if(_bSyncData) {
      uint8_t nPackIdx = rcvData[1];
      if(nPackIdx >= __nSyncPackCount)
        return;
      if(nPackIdx == 0x05 && _aSyncCheckSum[nPackIdx] == rcvData[nDataLen-1]) {
        [self sendDataBakToHrmForClear: nIdx char:pChar];
      }
      
      AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
      BOOL bNewSyncMeas = nPackIdx == 0x01;
      int nStart = bNewSyncMeas?6:2;
      _bNewSyncMeas = bNewSyncMeas;

      BOOL bNeedInsNew = bNewSyncMeas;
      NSDate* dtMeas = nil;
      NSUInteger nSyncCurtUtc = 0;
      if(bNewSyncMeas) {
        if(_nLastSyncPos == d0) {
          [self sendDataBakToHrmForClear: nIdx char:pChar];
          return;
        }
        
        nSyncCurtUtc = (rcvData[2] << 24) + (rcvData[3] << 16) + (rcvData[4] << 8) + rcvData[5];
        
        //nAddIdx = 0;
        dtMeas = [NSDate dateWithTimeIntervalSince1970:(NSTimeInterval)nSyncCurtUtc];
      
          
        if(nSyncCurtUtc > 0 && _nSyncStartUtc > 0 && _nSyncLastUtc > 0) {
          bNeedInsNew = (int)(nSyncCurtUtc - _nSyncStartUtc) > 179 && (int)(nSyncCurtUtc - _nSyncLastUtc > 119);
          //bNeedInsNew = (nSyncCurtUtc > _nSyncLastUtc) && [dtMeas timeIntervalSinceDate:_dtLastSync] > 9;
        }
        //_nSyncStartUtc = nSyncCurtUtc;

        
        //if(dtMeas != nil)
          //_dtLastSync = [dtMeas dateByAddingTimeInterval:0];;
      }
    
      if(dtMeas != nil) { //&& ![dtMeas isEqual: _dtSyncStart]
        if(bNeedInsNew) {
          _nLastSyncPos = d0;
          _nSyncLastUtc = nSyncCurtUtc;
          _nSyncStartUtc = nSyncCurtUtc;
          
          _dtSyncStart = [NSDate dateWithTimeIntervalSince1970:(NSTimeInterval)nSyncCurtUtc];
          if(_hRate != nil && _dtLastSync != nil && _nHrateId != 0 && _nLastHrate > 0) {
            [self updateHrateItemEndTime: pApp meas:_dtLastSync];
          }
          else { //chek if sync complete
            H_Rate* pHrate = [pApp loadHrateStartRcd:_nBodyId start:_dtSyncStart];
            if(pHrate != nil) {
              //NSInteger nLastIdx = pHrate.nLastUpdIdx.integerValue;
              NSUserDefaults *userSetting = [NSUserDefaults standardUserDefaults];
              int nLastIdx = (int)[userSetting integerForKey:kSync_LastDldIdx];
              if(nLastIdx == -1 || nLastIdx == -3) {
                _bSyncDevStop = YES;
                return;
              }
            }
          }
          
          _hRate = nil;
          _bSyncData = YES;
          _bStoredData = NO;//((nSyncCurtUtc > _nSyncLastUtc) && (int)(nSyncCurtUtc - _nSyncLastUtc) > 149)?NO: YES;
          
          _dtLastSync = [NSDate dateWithTimeIntervalSince1970:(NSTimeInterval)nSyncCurtUtc];//dtMeas;
          
          if([self insertStartHRMData:dtMeas]) {
            _nDownloadIdx = 0;
            short nHrate = rcvData[nStart];
            [pApp insertHrateItemData:_nHrateId bodyId:_nBodyId hRate:nHrate dtime: dtMeas toSvr: NO];
            
            //reset init pos
            NSUserDefaults *userSetting = [NSUserDefaults standardUserDefaults];
            [userSetting setInteger:0 forKey: kSync_LastMemDldIdx];
            [userSetting synchronize];
            _nLastIdx = 0;
            _nInitIdx = 0;
          }
          
          _dAvgHrate = 0.0;
          _nAvgHrate = 0;
          _nMaxHrate = 0;
          _nMinHrate = 1000;
          _fBurnedVal = 0.0;
          _nCountTick = 0;
          [self resetCtrlsDate];
        
          _dtMeasStart = [dtMeas dateByAddingTimeInterval:0];
          _dtMeas = [_dtMeasStart dateByAddingTimeInterval:0];
          
          //debug
          //[_ncitBleDev sendDebugHrate:0 dtStart:dtMeas dtEnd: _dtLastSync count:0];
          //debug
        
          _bSyncSentEndDataToSvr = NO;
          //_dtLastSync = [dtMeas dateByAddingTimeInterval:0];//[dtMeas initWithTimeIntervalSinceReferenceDate:0];
          _dtLastSync = [NSDate dateWithTimeIntervalSince1970:(NSTimeInterval)nSyncCurtUtc];
        }
      }
      
      if(nPackIdx == 0x05) {
        _nSyncLastUtc = 0;
        [self sendDataBakToHrmForClear: nIdx char:pChar];
        return;
      }
      
      //if(nDataLen != 4 && nPackIdx != 5 &&_nSyncLastUtc == 0)
        //return;
      
      BOOL bGetData = NO;
      if(nDataLen != 4 && nPackIdx != 5) {
        if(_bSyncDataError && [dtMeas timeIntervalSinceDate:_dtLastSync] <= 0)
          return;
        
       
        //NSDate* dtEnd = nil;
        //H_Rate* pHrate = nil;
        for(int i=nStart; i<nDataLen-1; i++) {
          short nHr = rcvData[i];
          _nLastHrate = nHr;
          if(nHr > 0 && _dtLastSync != nil && _nHrateId != 0)  {
            _bSyncSentEndDataToSvr = NO;
            //[self addHrateSyncVal:nHr];
            
            //nSyncCurtUtc += 2;
            _nSyncLastUtc += 2;
            _nSyncItemCount++;
            _nSyncTotalCount++;
            _dtLastSync = [NSDate dateWithTimeIntervalSince1970:(NSTimeInterval)_nSyncLastUtc];
            
            short nBpm = 0;
            if(_hRate != nil && _nDownloadIdx >= _nInitIdx &&& _nHrateId != 0) {
              nBpm = nHr;
            }
            
            // && [_dtLastSync timeIntervalSinceDate:_dtSyncStart] < 179
            if(_dtLastSync != nil && _hRate != nil && _nHrateId != 0) {
              [pApp insertHrateItemData:_nHrateId bodyId:_nBodyId hRate:nBpm dtime: _dtLastSync toSvr: NO];
              [pApp updHrateStartEndTime:_hRate startTime: nil endTime:_dtLastSync toSvr:NO];
              bGetData = YES;
            }
            else if(_hRate == nil ||  _nHrateId == 0) {
              [pApp showAlertBox:@"_hRate == nil & _nHrateId == 0" msg:@"Hrat data store issues!"];
               bGetData = NO;
            }
          }
        }
        //if(dtEnd != nil && pHrate != nil)
          //[pApp updHrateStartEndTime:pHrate startTime:dtEnd endTime:nil toSvr:NO];

        //_aSyncCheckSum[nPackIdx] = rcvData[nDataLen-1];
        
        _nDownloadIdx++;
        _nSyncPackIdx++;
      }
      //debug end date time
      //if(nDataLen == 4)
        //[_ncitBleDev sendDebugHrate: -1 dtStart:nil dtEnd:_dtLastSync count:-1];
      //debug
        
      _nLastSyncIdx = nPackIdx;
      
      //!_bSyncDevStop && _nDownloadIdx >= _nInitIdx && _dtLastSync != nil && _nHrateId != 0*
      if(bGetData && !_bSyncDevStop && _nDownloadIdx >= _nInitIdx && _dtLastSync != nil && _hRate != nil && _nHrateId != 0) {
        NSString* sMsg = [NSString stringWithFormat:@"Downloading Memory (%i)", _nDownloadIdx];
        [self performSelectorInBackground:@selector(showSyncMessage:) withObject:sMsg];
      }
      else if(_nDownloadIdx < _nInitIdx) {
        NSString* sMsg = _lblMsg.text;
        if([sMsg rangeOfString:@"Downloading"].location == NSNotFound) {
          sMsg = @"Check Break Point Data...";
          [self performSelectorInBackground:@selector(showSyncMessage:) withObject:sMsg];
        }
      }
    }*/
}

- (void) syncHrateProg
{
    _lblMsg.text = [NSString stringWithFormat:@"Sync packet %d...", _nLastSyncIdx];
}

- (void) syncCycleData:(uint8_t) d0 char:(CBCharacteristic*)aChar
{
    uint8_t nIdx = d0 >> 4;
    
    uint8_t val[4] = {0xe0, nIdx, 0x00, 0x00};
    val[3] = [self getCheckSum:val len:3];
    
    NSData* valData = [NSData dataWithBytes:(void*)val length:sizeof(val)];
    [_ncitBleDev sendDataToBleDev:aChar data:valData type: CBCharacteristicWriteWithoutResponse];
    
    NSLog(@"Send Cycle Sync Data: %X", val[0]);
}

- (void) returnDevOk:(uint8_t) d0 char:(CBCharacteristic*)aChar
{
    uint8_t nIdx = d0 >> 4;
  
    uint8_t val[4] = {0xe0, nIdx, 0x00, 0x00};
    val[3] = [self getCheckSum:val len:3];
    
    NSData* valData = [NSData dataWithBytes:(void*)val length:sizeof(val)];
    [_ncitBleDev sendDataToBleDev:aChar data:valData type: CBCharacteristicWriteWithoutResponse];
    
    //NSLog(@"return OK!");
    
    if(_actView != nil) {
        [_actView stopAnimating];
        _actView.hidden = YES;
    }
    //_btnSyncTpp.hidden = NO;
    _btnStartStop.hidden = NO;
  
  self.navigationItem.hidesBackButton = NO;
  self.navigationController.interactivePopGestureRecognizer.enabled = YES;
}

-(void) endOneSyncData:(short)nBpm
{
    if(_nHrateId != 0) {
      //debug
      if(!_bSyncSentEndDataToSvr) {
        //[_ncitBleDev sendDebugHrate:0 dtStart:_dtSyncStart dtEnd: _dtLastSync count:0];
        _bSyncSentEndDataToSvr = YES;
      }
      //debug

      
      AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
      [self storeRateRngData: NO];
      pApp.m_nHrateId = 0;
      //_nHrateId = 0;
      
      _nDownloadIdx = 0;
        
      _bNewSyncMeas = NO;
      _dtSyncStart = nil;
      _nLastSyncHrate = 0;
      _nLastSyncIdx = -1;
      _nSyncItemCount = 0;
      
      _nSyncStartUtc = 0;
      _nSyncLastUtc = 0;
      _bStoredData = NO;
      
      _nPastHrateId = 0;
      
      //_dtLastSync = nil;
      //_hRate = nil;
      
      for(int i=0; i<6; i++) {
        _aSyncCheckSum[i] = 0;
      }
      
      //NSString* sHrateId = [NSString stringWithFormat:@"%ld", (long)_nHrateId];
      //[pApp updHrateSyncLastIdx: sHrateId lastIdx:-3];
    }
}

- (void) bleDisconnected
{
  if(!_bBleConnException)
    [self insertHrateDataToDatabase];
    
  if(_actView != nil) {
    [_actView stopAnimating];
    _actView.hidden = YES;
  }

  /*else if(!_bSyncData &&  !_bJustStart && _ncitBleDev.bSyncDevData) {
    _lblMsg.text = @"HRM init completed, Tap play to go";
  }
  else {
    _lblMsg.text = @"HM Disconnected!";
  }*/
    
  UIImage* iBtn = [UIImage imageNamed:@"btn-start.png"];
  [_btnStartStop setBackgroundImage:iBtn forState:UIControlStateNormal];
    _btnStartStop.imageView.contentMode = UIViewContentModeScaleAspectFit;
  _lblStartStop.text = @"START";
  
  NSString* sBleName = [_ncitBleDev getBlePerName];
  if(_bStartBleMeas && ([sBleName hasPrefix:@"Smart"] || [sBleName isEqualToString:@"OTbeat"])) {
    _lblMsg.text = NSLocalizedString(@"Please wait...", nil);
    _ncitBleDev.bleDelegate = self;
    [_ncitBleDev loadSavedDevice:0];
  }
  //_bStartBleMeas = NO;
  _btnStartStop.hidden = NO;
  _bStartBleMeas = NO;
  AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  if(pApp.m_bSupportBle) {
    //_ncitBleDev.bleDelegate = nil;
    _lblMsg.text = NSLocalizedString(@"BLE Disconnected!", nil);
  }
  
  if(_nHrateId != 0) {
    AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    if(_hRate != nil) {
      //if([self needUpdHrtEndtime])
      NSDate* dtMeas = _bSyncData?_dtLastSync: _dtMeas;
      if(dtMeas != nil) {
        [pApp updHrateStartEndTime:_hRate startTime: nil endTime:dtMeas toSvr:!_bSyncData];
        [pApp insertHrateItemData:_nHrateId bodyId:_nBodyId hRate:_nLastHrate dtime: dtMeas toSvr: !_bSyncData];
      }
      [self storeRateRngData:YES];
    }
    
    if(_hRate != nil) {
      _dtMeas = [NSDate date];
      [self storeRateRngData:YES];
   
      //if(_bSyncData) {
      //[pApp updHrateStartEndTime:_hRate startTime:nil endTime:_bSyncData?_dtLastSync:_dtMeas toSvr:NO];
      _bSyncData = NO;
      //}
      
      if(_dtLastSync != nil || !_bSyncData) {
        _nHrateId = 0;
        _hRate = nil;
      }
    }
    
    if(_bSyncData) {
      if(_bSyncException) {
        _bStartBleMeas = NO;
        _lblMsg.text = NSLocalizedString(@"Sync not complete", nil);
      }
      else {
        if(_dtLastSync != nil) {
          [self endOneSyncData:0];
          _dtLastSync = nil;
        }
        _lblMsg.text = [NSString stringWithFormat:NSLocalizedString(@"Sync Completed (%i)!", nil), _nSyncTotalCount];
      }
    }
  }
  
  if(_nDownloadMemHrateId < 0 && _nDownloadIdx > 0) {
    NSString* sHrateId = [NSString stringWithFormat:@"%ld", (long)_nDownloadMemHrateId];
    [pApp updHrateSyncLastIdx: sHrateId lastIdx:_nDownloadIdx-1];
    
    NSUserDefaults *userSetting = [NSUserDefaults standardUserDefaults];
    [userSetting setInteger:_nDownloadIdx-1 forKey: kSync_LastMemDldIdx];
    [userSetting synchronize];
    _nLastIdx = _nDownloadIdx - 1;
  }
  _nLastHrate = -1;
  
  _bSyncData = NO;
  _bContBleDev = NO;
  _bDownloadMemEnd = NO;
  _bBleConnException = YES;
  
  self.navigationItem.hidesBackButton = NO;
  self.navigationController.interactivePopGestureRecognizer.enabled = YES;
}

- (void) bleUserClosed
{
  _bBleConnException = YES;
  [self insertHrateDataToDatabase];
  
  _ncitBleDev.bleDelegate = nil;
  AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  _lblMsg.text = (pApp.m_bSupportBle)? NSLocalizedString(@"BLE Disconnected!", nil): NSLocalizedString(@"BLE Closed, Session Ended", nil);
  
  if(self.navigationItem.hidesBackButton/*_bSyncData*/) {
    //_bSyncData = NO;
    self.navigationItem.hidesBackButton = NO;
    //self.navigationController.interactivePopGestureRecognizer.enabled = YES;
  }
  
  //NSString* sHrateId = [NSString stringWithFormat:@"%ld", (long)_nDownloadMemHrateId];
  //[pApp updHrateSyncLastIdx: sHrateId lastIdx:_nDownloadIdx-1];
  
  _bSyncData = NO;
  _hRate = nil;
  _nHrateId = 0;
  pApp.m_nHrateId = 0;
  //[self stopActindicator:nil];
  [self performSelectorOnMainThread:@selector(stopActindicator:) withObject:NSLocalizedString(@"BLE Conn Exception...", nil) waitUntilDone:YES];
  AudioServicesPlaySystemSound(1112);
}

//store core data
-(BOOL) storeRateRngData:(BOOL)bToSvr
{
  //_nDownloadMemHrateId = _nHrateId;
  if(_nHrateId < 0)
    return NO;
  
    if(_nBodyId == 0 || _nHrateId == 0 || _nLastHrate == 0)
        return NO;
    AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    //NSDateFormatter* dtFmt = pApp.dtFmt;
    NSMutableArray* rateDate = [NSMutableArray arrayWithArray:[pApp loadHrateItemData:_nHrateId last:NO]];
    if(rateDate == nil || rateDate.count == 0)
        return NO;
    
    /*short nMaxHrt = 210 - _nAgeYear / 2 - _BodyWgt * 0.05;
    if(_nSexNum == 1)
        nMaxHrt += 4;*/
    //short nRngLow = (short)(_fRngLow + 0.5);
    //short nRngUpp = (short)(_fRngUpp + 0.5);
  short nRngLow = (short)(_fCalRngLow + 0.5);
  short nRngUpp = (short)(_fCalRngUpp + 0.5);
  
    //NSDate* dtLast = [NSdate date];
    float fLowMinuts = 0, fMidMinuts=0, fHgtMinuts = 0;
    float fCalLow = 0, fCalMid = 0, fCalHgt = 0;
    short nLastIdx = 0;
    
    float fCalories = 0.0;
    NSUInteger nCount = rateDate.count;
    if(nCount > 0) {
        H_RateItem* hrItem = (H_RateItem*)[rateDate objectAtIndex:0];
        _dtLast = hrItem.hRateTime;
        short nHrate = [hrItem.hRateValue shortValue];
        fCalories = [self calBurnedCalories:nHrate second:2.0 wgt:_fBodyWgt age:_nAgeYear sex:_nSexNum];
    }
    //int nNum = 0;
    for(NSUInteger i=1; i<nCount; i++) {
        //nNum++;
        if(_dtLast == nil)
            continue;
        
        double dDurSeconds = 0;
        H_RateItem* hrItem = (H_RateItem*)[rateDate objectAtIndex:i];
        short nRate = [hrItem.hRateValue shortValue];
        if(nRate < nRngLow) {
            nLastIdx = 1;
        }
        else if((nRate >= nRngLow) && (nRate <= nRngUpp)) {
            nLastIdx = 2;
        }
        else {
            nLastIdx = 3;
        }
        
        NSDate* dt = hrItem.hRateTime;
        if(_dtLast != nil) {
          dDurSeconds = [dt timeIntervalSinceDate:_dtLast];
          if(dDurSeconds < 0)
            dDurSeconds = 2;
            
          if(nLastIdx == 1)
            fLowMinuts += dDurSeconds;
          else if(nLastIdx == 2)
            fMidMinuts += dDurSeconds;
          else if(nLastIdx == 3)
            fHgtMinuts += dDurSeconds;
        }
        
        
        //calories burned
        
        fCalories += [self calBurnedCalories:nRate second:dDurSeconds wgt:_fBodyWgt age:_nAgeYear sex:_nSexNum];
        /*if(_nSexNum == 1)
         fCalories = ((-55.0969 + 0.6309 * nRate - 0.09036 * _BodyWgt + 0.2017 * _nAgeYear) / 4.184) * (dDurSeconds / 60) / 1000;
         else
         fCalories = ((-20.4022 + 0.4472 * nRate - 0.05741 * _BodyWgt + 0.074 * _nAgeYear) / 4.184) * (dDurSeconds / 60) / 1000;
         if(fCalories < 0)
         fCalories = 0;*/
        
        if(nLastIdx == 1)
            fCalLow += fCalories;
        else if(nLastIdx == 2)
            fCalMid += fCalories;
        else if(nLastIdx == 3)
            fCalHgt += fCalories;
        
        
        fCalories = 0;
        _dtLast = dt;//[_dtLast dateByAddingTimeInterval:dDurSeconds];
    }
    //_lblHrateVal.text = [NSString stringWithFormat:@"%.0f C", (fCalLow + fCalMid + fCalHgt) * 1000];
    
    if(fCalLow < 0)
        fCalLow = 0.0;
    if(fCalMid < 0)
        fCalMid = 0.0;
    if(fCalHgt < 0)
        fCalHgt = 0.0;
    
    NSDate* dtMeas = _dtMeasStart;//[NSDate date];
    fLowMinuts /= 60.0;
    fMidMinuts /= 60.0;
    fHgtMinuts /= 60.0;
    //BOOL bNeedSave = (_nHrateId > 0) && (fLowMinuts > 0 || fMidMinuts > 0 || fHgtMinuts > 0);
  
    //has changed svr
    /*bool bResolved = NO;
    if(bNeedSave) {
        //send to svr
        bResolved = pApp.m_bHostConn;
        if(!bResolved)
            bResolved = [pApp ConnScaleHost:YES IpAddr: NULL];
        NSDateFormatter* _dtFormat = pApp.dtFmt;
        
        //NSInteger nId = 0;
        if(bResolved) {
            NSString* sBleHrate = [NSString stringWithFormat:@"2262 NCIT-BLE-HRATE %li %ld %i %i %.2f %.2f %.2f %.4f %.4f %.4f ", (long)_nBodyId,
                                   (long)_nHrateId, nRngLow, nRngUpp, fLowMinuts, fMidMinuts, fHgtMinuts, fCalLow, fCalMid, fCalHgt];
            sBleHrate = [sBleHrate stringByAppendingString: [_dtFormat stringFromDate:dtMeas]];
            sBleHrate = [sBleHrate stringByAppendingString:@"\r\n"];
            [pApp.m_ncitWiFiDev sendData:(char*)[sBleHrate UTF8String] Alert:NO];
        }
    }*/
    
    //local store
    //NSInteger nId = 0;
    //low rate
    NSString* sRateRngText = [NSString stringWithFormat:@"< %d bpm", nRngLow];
    if(fLowMinuts >= 0.0001)
        [pApp insertHrateRngData:_nHrateId bodyId:_nBodyId idx:1 rng:sRateRngText dur:fLowMinuts cal:fCalLow dtVal:dtMeas toSvr:bToSvr];
    //mid rate
    if( fMidMinuts >= 0.0001) {
        sRateRngText = [NSString stringWithFormat:@"%d ~ %d bpm", nRngLow, nRngUpp];
        [pApp insertHrateRngData:_nHrateId bodyId:_nBodyId idx:2 rng:sRateRngText dur:fMidMinuts cal:fCalMid dtVal:dtMeas toSvr:bToSvr];
    }
    //mid rate
    if(fHgtMinuts >= 0.0001) {
        sRateRngText = [NSString stringWithFormat:@"> %d bpm", nRngUpp];
        [pApp insertHrateRngData:_nHrateId bodyId:_nBodyId idx:3 rng:sRateRngText dur:fHgtMinuts cal:fCalHgt dtVal:dtMeas toSvr:bToSvr];
    }
  
    //for rate over view. no svr
    /*if(bNeedSave && _nAvgHrate > 0 && bResolved) {
        //rate over view data
        NSString* sHrateOview = [NSString stringWithFormat:@"2262 BLE-HRATE-OVIEW %ld %ld %i %i %i ", (long)_nBodyId,
                                 (long)_nHrateId, _nAvgHrate, _nMaxHrate, _nMinHrate];
        sHrateOview = [sHrateOview stringByAppendingString: [dtFmt stringFromDate:_dtMeasStart]];
        sHrateOview = [sHrateOview stringByAppendingString:@" "];
        sHrateOview = [sHrateOview stringByAppendingString: [dtFmt stringFromDate:dtMeas]];
        sHrateOview = [sHrateOview stringByAppendingString:@"\r\n"];
        [pApp.m_ncitWiFiDev sendData:(char*)[sHrateOview UTF8String] Alert:NO];
        _dtMeasEnd = dtMeas;
    }*/
  //_nHrateId = 0;
  //_nLastHrate = 0;
  //_nPastHrateId = 0;
  /*if(bResolved) {
    //[pApp CloseScaleHost];
  }*/
  
  //if(!bToSvr)®
    //[self endOneSyncData:0];
  return YES;
}

/**************************/
/* data source and delete */
/**************************/
- (CGFloat) getBarHgtMax{
  CGFloat fMaxVal = 0;
  for (NSInteger i=0; i<_nDurtBarNumber; i++) {
    //if(fMaxVal < _faHrate[i] * _afPointCoef[i])
      //fMaxVal = _faHrate[i] * _afPointCoef[i];
    if(fMaxVal < _faHrate[i])
      fMaxVal = _faHrate[i];
  }
  
  if(fMaxVal > 0) {
    BOOL bNormized = fMaxVal > _BarHgtUpLimit;
    for (NSInteger i=0; i<_nDurtBarNumber; i++) {
      if(bNormized)
        _faHrtHgt[i] = _faHrate[i] * _BarHgtUpLimit / fMaxVal;
      else
        _faHrtHgt[i] = _faHrate[i] / 2.5;
      
      //_faHrtHgt[i] *= _afPointCoef[i];
    }
  }
  
  return fMaxVal;
}

- (NSUInteger)numberOfBarsInBarChart:(UICurveView *)barChart
{
    return _nDurtBarNumber;
}

- (CGFloat)barChart:(UICurveView *)barChart valueForBarAtIndex:(NSUInteger)index
{
  return _faHrtHgt[index];
  
    /*CGFloat fTime = _faHrate[index];
    if(fTime >= 100) {
        int nTime = fTime;
        CGFloat fDecimal = fTime - nTime;
        nTime = nTime % 100;
        fTime = nTime + fDecimal;
    }
    fTime /= 2.5;
    return fTime;*/
}

- (CGFloat)barChart:(UICurveView *)barChart xposForBarAtIndex:(NSUInteger)index
{
    CGFloat xPos = index * 10;
    return xPos;
}

/*- (UIColor *)barChartColor:(NSInteger)nIdx
{
    return _barColors[nIdx];
}*/

/*- (short)barChart:(UICurveView *)barChart hRateForBarAtIndex:(NSUInteger)index
{
    return 10 * index;
}*/

- (UIColor *)barChart:(UICurveView *)barChart colorForBarAtIndex:(NSUInteger)index
{
    return [UIColor redColor];
}

- (NSString *)barChart:(UICurveView *)barChart xLabelForBarAtIndex:(NSUInteger)index
{
    return @"4.5";
}

- (NSString *)barChart:(UICurveView *)barChart textForBarAtIndex:(NSUInteger)index
{
    return @"50";
}

- (int) totalRcvedCount
{
    return _nCountTick;
}

- (double) HrateTimeInterval
{
  return _dMeasInterval;
}

/*- (UIColor *)barChart:(UICurveView *)barChart colorForBarAtIndex:(NSUInteger)index
{
 
}
- (void) EnableDownloadHrmMemory
{
  _lblMsg.text = @"Eablle down Memory";
}*/


@end
